diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/builders/ArrayListBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/builders/ArrayListBuilder.java new file mode 100644 index 00000000..24cd7bc6 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/builders/ArrayListBuilder.java @@ -0,0 +1,90 @@ +/* + * 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.builders; + +import java.util.ArrayList; +import java.util.List; + +/** + * Generic Builder for Lists. Helperclass for being able to provide functional interfaces in + * extending lists. Using ArrayLists inside. + * + *

Origin: copied from {@code + * org.javahelpers.simple.builders.core.builders.ArrayListBuilder} of simple-builders-core so that + * codegen-core does not depend on the builders runtime module. The DTO builders committed in this + * module must work without forcing a simple-builders-core dependency onto codegen users. + * + * @param the type of elements in the targeting list + */ +public class ArrayListBuilder { + private final List mList = new ArrayList<>(); + + /** Creates an empty ArrayListBuilder. */ + public ArrayListBuilder() {} + + /** + * Creates an ArrayListBuilder initialized with the elements from the given list. + * + * @param initialList list to initialize from + */ + public ArrayListBuilder(List initialList) { + if (initialList != null) { + mList.addAll(initialList); + } + } + + /** + * Appends the element to the end of the internal list. Calling add-function on inner ArrayList + * field. + * + * @param element Element to be appended + * @return current instance of ArrayListBuilder for using in stream-notation + */ + public ArrayListBuilder add(T element) { + mList.add(element); + return this; + } + + /** + * Appends a list of elements to the end of the internal list. Calling addAll-function on inner + * ArrayList field. + * + * @param elements list of Elements to be appended + * @return current instance of ArrayListBuilder for using in stream-notation + */ + public ArrayListBuilder addAll(List elements) { + mList.addAll(elements); + return this; + } + + /** + * Builds a new list based on the elements appended by the other functions. + * + * @return new ArrayList holding all elements which have been added before + */ + public List build() { + return new ArrayList<>(mList); + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/builders/ArrayListBuilderWithElementBuilders.java b/codegen-core/src/main/java/org/javahelpers/codegen/builders/ArrayListBuilderWithElementBuilders.java new file mode 100644 index 00000000..07342916 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/builders/ArrayListBuilderWithElementBuilders.java @@ -0,0 +1,117 @@ +/* + * 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.builders; + +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Enhanced builder for Lists that supports adding elements via builder consumers. This class + * extends {@link ArrayListBuilder} and adds methods to accept {@link Consumer} functions that + * configure element builders, eliminating the need to manually call {@code build()} on each element + * builder. + * + *

Example usage: + * + *

{@code
+ * List people = new ArrayListBuilderWithElementBuilders<>(PersonBuilder::create)
+ *     .add(personBuilder -> personBuilder
+ *         .name("John Doe")
+ *         .age(30))
+ *     .add(personBuilder -> personBuilder
+ *         .name("Jane Smith")
+ *         .age(25))
+ *     .build();
+ * }
+ * + *

Origin: copied from {@code + * org.javahelpers.simple.builders.core.builders.ArrayListBuilderWithElementBuilders} of + * simple-builders-core so that codegen-core does not depend on the builders runtime module. The DTO + * builders committed in this module must work without forcing a simple-builders-core dependency + * onto codegen users. + * + * @param the type of elements in the targeting list + * @param the type of builder used to create elements, must implement {@link IBuilderBase} and + * building objects of type T + */ +public class ArrayListBuilderWithElementBuilders> + extends ArrayListBuilder { + private final Supplier elementBuilderProvider; + + /** + * Creates an empty ArrayListBuilderWithElementBuilders. + * + * @param elementBuilderProvider supplier that provides new instances of element builders + */ + public ArrayListBuilderWithElementBuilders(Supplier elementBuilderProvider) { + this.elementBuilderProvider = elementBuilderProvider; + } + + /** + * Creates an ArrayListBuilderWithElementBuilders initialized with the elements from the given + * list. + * + * @param initialList list to initialize from + * @param elementBuilderProvider supplier that provides new instances of element builders + */ + public ArrayListBuilderWithElementBuilders( + List initialList, Supplier elementBuilderProvider) { + super(initialList); + this.elementBuilderProvider = elementBuilderProvider; + } + + /** + * Adds an element to the list by providing a consumer that configures an element builder. The + * builder is automatically created using the elementBuilderProvider and built after + * configuration. + * + * @param elementBuilderConsumer consumer that configures the element builder + * @return this builder instance for method chaining + */ + public ArrayListBuilderWithElementBuilders add(Consumer elementBuilderConsumer) { + B elementBuilder = elementBuilderProvider.get(); + elementBuilderConsumer.accept(elementBuilder); + super.add(elementBuilder.build()); + return this; + } + + /** + * Adds multiple elements to the list by providing consumers that configure element builders. Each + * builder is automatically created using the elementBuilderProvider and built after + * configuration. + * + * @param elementBuilderConsumers varargs of consumers that configure element builders + * @return this builder instance for method chaining + */ + @SafeVarargs + public final ArrayListBuilderWithElementBuilders add( + Consumer... elementBuilderConsumers) { + for (Consumer elementBuilderConsumer : elementBuilderConsumers) { + this.add(elementBuilderConsumer); + } + return this; + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/builders/BuilderToStringStyle.java b/codegen-core/src/main/java/org/javahelpers/codegen/builders/BuilderToStringStyle.java new file mode 100644 index 00000000..933157f4 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/builders/BuilderToStringStyle.java @@ -0,0 +1,63 @@ +/* + * 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.builders; + +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * Custom ToStringStyle for builders that automatically handles TrackedValue fields. This style only + * includes fields that have been set (TrackedValue.isSet() returns true) and unwraps their values + * automatically. + * + *

Origin: copied from {@code + * org.javahelpers.simple.builders.core.util.BuilderToStringStyle} of simple-builders-core so that + * codegen-core does not depend on the builders runtime module. The DTO builders committed in this + * module must work without forcing a simple-builders-core dependency onto codegen users. + */ +public class BuilderToStringStyle extends ToStringStyle { + + private static final long serialVersionUID = 1L; + + public static final BuilderToStringStyle INSTANCE = new BuilderToStringStyle(); + + public BuilderToStringStyle() { + super(); + this.setUseClassName(true); + this.setUseIdentityHashCode(false); + } + + // Overrides ToStringStyle.append to unwrap TrackedValue fields; the signature must match the + // overridden method. codeql[java/confusing-method-signature] + @Override + public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) { + if (value instanceof TrackedValue trackedValue) { + if (trackedValue.isSet()) { + super.append(buffer, fieldName, trackedValue.value(), fullDetail); + } + } else { + super.append(buffer, fieldName, value, fullDetail); + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/builders/HashMapBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/builders/HashMapBuilder.java new file mode 100644 index 00000000..533a13a9 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/builders/HashMapBuilder.java @@ -0,0 +1,122 @@ +/* + * 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.builders; + +import java.util.HashMap; +import java.util.Map; + +/** + * Generic Builder for Maps. Helperclass for being able to provide functional interfaces in + * extending maps. Using HashMap inside. + * + *

Origin: copied from {@code + * org.javahelpers.simple.builders.core.builders.HashMapBuilder} of simple-builders-core so that + * codegen-core does not depend on the builders runtime module. The DTO builders committed in this + * module must work without forcing a simple-builders-core dependency onto codegen users. + * + * @param the type of keys in the targeting map + * @param the type of values in the targeting map + */ +public class HashMapBuilder { + private final Map mMap = new HashMap<>(); + + /** Creates an empty HashMapBuilder. */ + public HashMapBuilder() {} + + /** + * Creates a HashMapBuilder initialized with the mappings from the given map. + * + * @param initialMap map to initialize from + */ + public HashMapBuilder(Map initialMap) { + if (initialMap != null) { + mMap.putAll(initialMap); + } + } + + /** + * Associates the specified value with the specified key in this map. Using an inner HashMap + * implementation. If the key already exists in the map, the old value is replaced. + * + * @param key key with which the specified value is to be associated + * @param value value to be associated with the specified key + * @return Current instance of HashMapBuilder for using in stream-notation + */ + public HashMapBuilder put(K key, V value) { + mMap.put(key, value); + return this; + } + + /** + * Associates the specified value with the specified key in this map, if the specified key is not + * already associated. Using an inner HashMap implementation. If {@code null} is associated with + * the specific key, it will be replaced. + * + * @param key key with which the specified value is to be associated + * @param value value to be associated with the specified key + * @return Current instance of HashMapBuilder for using in stream-notation + */ + public HashMapBuilder putIfAbsent(K key, V value) { + mMap.putIfAbsent(key, value); + return this; + } + + /** + * Associates the specified value with the specified key in this map, if the specified value is + * not null. Using an inner HashMap implementation. + * + * @param key key with which the specified value is to be associated + * @param value value to be associated with the specified key + * @return Current instance of HashMapBuilder for using in stream-notation + */ + public HashMapBuilder putIfValueNotNull(K key, V value) { + if (value != null) { + mMap.put(key, value); + } + return this; + } + + /** + * Copies all of the mappings from the specified map to the inner map of Builder. Using an inner + * HashMap implementation. These mappings will replace any mappings that the inner map of + * HashMapBuilder had before. + * + * @param pMap mappings to be added to HashMapBuilder + * @return Current instance of HashMapBuilder for method chaining + */ + public HashMapBuilder putAll(Map pMap) { + mMap.putAll(pMap); + return this; + } + + /** + * Builds a new Map based on the mappings defined by the other functions. + * + * @return new HashMap holding all mappings which have been defined before + */ + public Map build() { + return new HashMap<>(mMap); + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/builders/HashSetBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/builders/HashSetBuilder.java new file mode 100644 index 00000000..4b4a7d3f --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/builders/HashSetBuilder.java @@ -0,0 +1,90 @@ +/* + * 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.builders; + +import java.util.HashSet; +import java.util.Set; + +/** + * Generic Builder for Sets. Helperclass for being able to provide stream-notation interfaces in + * extending setws. Using HashSet inside. + * + *

Origin: copied from {@code + * org.javahelpers.simple.builders.core.builders.HashSetBuilder} of simple-builders-core so that + * codegen-core does not depend on the builders runtime module. The DTO builders committed in this + * module must work without forcing a simple-builders-core dependency onto codegen users. + * + * @param the type of elements in the targeting Set + */ +public class HashSetBuilder { + private final Set mSet = new HashSet<>(); + + /** Creates an empty HashSetBuilder. */ + public HashSetBuilder() {} + + /** + * Creates a HashSetBuilder initialized with the elements from the given set. + * + * @param initialSet set to initialize from + */ + public HashSetBuilder(Set initialSet) { + if (initialSet != null) { + mSet.addAll(initialSet); + } + } + + /** + * Appends the element to the internal set. Calling add-function on inner HashSet field. + * + * @param element element to be appended + * @return current instance of ArrayListBuilder for using in stream-notation + */ + public HashSetBuilder add(T element) { + mSet.add(element); + return this; + } + + /** + * Appends a list of elements to the end of the internal list. Calling addAll-function on inner + * HashSet field. + * + * @param elements Set of elements to be appended + * @return current instance of HashSetBuilder for using in stream-notation + */ + public HashSetBuilder addAll(Set elements) { + mSet.addAll(elements); + return this; + } + + /** + * Builds a new Set containing all elements that have been added to this builder. The returned Set + * is a new instance, so subsequent modifications to the builder will not affect the returned Set. + * + * @return a new HashSet containing all elements added to this builder + */ + public Set build() { + return new HashSet<>(mSet); + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/builders/HashSetBuilderWithElementBuilders.java b/codegen-core/src/main/java/org/javahelpers/codegen/builders/HashSetBuilderWithElementBuilders.java new file mode 100644 index 00000000..92de0ab2 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/builders/HashSetBuilderWithElementBuilders.java @@ -0,0 +1,113 @@ +/* + * 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.builders; + +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Enhanced builder for Sets that supports adding elements via builder consumers. This class extends + * {@link HashSetBuilder} and adds methods to accept {@link Consumer} functions that configure + * element builders, eliminating the need to manually call {@code build()} on each element builder. + * + *

Example usage: + * + *

{@code
+ * Set people = new HashSetBuilderWithElementBuilders<>(PersonBuilder::create)
+ *     .add(personBuilder -> personBuilder
+ *         .name("John Doe")
+ *         .age(30))
+ *     .add(personBuilder -> personBuilder
+ *         .name("Jane Smith")
+ *         .age(25))
+ *     .build();
+ * }
+ * + *

Origin: copied from {@code + * org.javahelpers.simple.builders.core.builders.HashSetBuilderWithElementBuilders} of + * simple-builders-core so that codegen-core does not depend on the builders runtime module. The DTO + * builders committed in this module must work without forcing a simple-builders-core dependency + * onto codegen users. + * + * @param the type of elements in the targeting set + * @param the type of builder used to create elements, must implement {@link IBuilderBase} and + * building objects of type T + */ +public class HashSetBuilderWithElementBuilders> + extends HashSetBuilder { + private final Supplier elementBuilderProvider; + + /** + * Creates an empty HashSetBuilderWithElementBuilders. + * + * @param elementBuilderProvider supplier that provides new instances of element builders + */ + public HashSetBuilderWithElementBuilders(Supplier elementBuilderProvider) { + this.elementBuilderProvider = elementBuilderProvider; + } + + /** + * Creates a HashSetBuilderWithElementBuilders initialized with the elements from the given set. + * + * @param initialSet set to initialize from + * @param elementBuilderProvider supplier that provides new instances of element builders + */ + public HashSetBuilderWithElementBuilders(Set initialSet, Supplier elementBuilderProvider) { + super(initialSet); + this.elementBuilderProvider = elementBuilderProvider; + } + + /** + * Adds an element to the set by providing a consumer that configures an element builder. The + * builder is automatically created using the elementBuilderProvider and built after + * configuration. + * + * @param elementBuilderConsumer consumer that configures the element builder + * @return this builder instance for method chaining + */ + public HashSetBuilderWithElementBuilders add(Consumer elementBuilderConsumer) { + B elementBuilder = elementBuilderProvider.get(); + elementBuilderConsumer.accept(elementBuilder); + super.add(elementBuilder.build()); + return this; + } + + /** + * Adds multiple elements to the set by providing consumers that configure element builders. Each + * builder is automatically created using the elementBuilderProvider and built after + * configuration. + * + * @param elementBuilderConsumers varargs of consumers that configure element builders + * @return this builder instance for method chaining + */ + @SafeVarargs + public final HashSetBuilderWithElementBuilders add(Consumer... elementBuilderConsumers) { + for (Consumer elementBuilderConsumer : elementBuilderConsumers) { + this.add(elementBuilderConsumer); + } + return this; + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/builders/IBuilderBase.java b/codegen-core/src/main/java/org/javahelpers/codegen/builders/IBuilderBase.java new file mode 100644 index 00000000..30b48f91 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/builders/IBuilderBase.java @@ -0,0 +1,44 @@ +/* + * 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.builders; + +/** + * Interface for all generated builders. + * + *

Origin: copied from {@code + * org.javahelpers.simple.builders.core.interfaces.IBuilderBase} of simple-builders-core so that + * codegen-core does not depend on the builders runtime module. The DTO builders committed in this + * module must work without forcing a simple-builders-core dependency onto codegen users. + * + * @param the type of build instances + */ +public interface IBuilderBase { + /** + * Baseinterface for all builders. + * + * @return building target of builder + */ + T build(); +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/builders/TrackedValue.java b/codegen-core/src/main/java/org/javahelpers/codegen/builders/TrackedValue.java new file mode 100644 index 00000000..68275757 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/builders/TrackedValue.java @@ -0,0 +1,154 @@ +/* + * 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.builders; + +import java.util.function.Consumer; + +/** + * Represents a value together with a flag indicating whether it has been explicitly changed. + * + *

This utility is used by generated builders to differentiate between: + * + *

+ * + * The {@code isChanged} flag controls whether setter invocations should be performed during {@code + * build()}; only changed values are applied. + * + *

Origin: copied from {@code org.javahelpers.simple.builders.core.util.TrackedValue} of + * simple-builders-core so that codegen-core does not depend on the builders runtime module. The DTO + * builders committed in this module must work without forcing a simple-builders-core dependency + * onto codegen users. + * + * @param the value type + * @param value the underlying value (may be {@code null}) + * @param isChanged whether the value was explicitly changed by the builder API + * @param isInitial whether the value is an initial value from an existing instance + */ +public record TrackedValue(T value, boolean isChanged, boolean isInitial) { + + /** + * Checks if this value has been set (either as initial value or changed). + * + * @return true if the value is set (initial or changed), false if unset + */ + public boolean isSet() { + return isChanged || isInitial; + } + + /** + * Returns the value if set, otherwise the given default. + * + * @param defaultValue the default to return if unset + * @return the value if set, otherwise the default + */ + public T valueOr(T defaultValue) { + return isSet() ? value : defaultValue; + } + + /** + * Executes the provided {@link Consumer} only if this value has been set (initial value or + * changed). Returns a {@link DefaultValueApplier} that can fluently provide a default via {@code + * .orElse(default)} if the value was unset. + * + *

Existing code that ignores the return value (e.g. {@code tracked.ifSet(consumer);}) + * continues to work unchanged. + * + * @param consumer action to perform with the current {@link #value()} + * @return a {@link DefaultValueApplier} for fluent default handling + */ + public DefaultValueApplier ifSet(Consumer consumer) { + if (isSet()) { + consumer.accept(value); + } + return new DefaultValueApplier<>(isSet(), consumer); + } + + /** + * Intermediate result returned by {@link #ifSet(Consumer)} to support fluent default-value + * application via {@code .orElse(default)}. + * + *

When {@link #ifSet(Consumer)} is called on a set {@link TrackedValue}, the consumer is + * invoked immediately and {@code alreadyApplied} is {@code true}, making the subsequent {@link + * #orElse(Object)} call a no-op. When called on an unset value, the consumer is not invoked and + * {@code alreadyApplied} is {@code false}, so {@link #orElse(Object)} applies the default value + * to the same consumer. + * + * @param the value type + * @param alreadyApplied whether the consumer has already been invoked + * @param consumer the consumer to apply the default value to if not already applied + */ + public record DefaultValueApplier(boolean alreadyApplied, Consumer consumer) { + + /** + * Applies the given default value to the consumer if the original value was unset. + * + * @param defaultValue the default value to apply + */ + public void orElse(T defaultValue) { + if (!alreadyApplied) { + consumer.accept(defaultValue); + } + } + } + + /** + * Creates a tracked value representing an unset state (no change made). + * + * @param the value type + * @return an instance with {@code value == null}, {@code isChanged == false}, and {@code + * isInitial == false} + */ + public static TrackedValue unsetValue() { + return new TrackedValue<>(null, false, false); + } + + /** + * Creates a tracked value representing an initial value copied from an existing instance. The + * value is present but is not considered a change initiated by the builder. + * + * @param the value type + * @param value the initial value (may be {@code null}) + * @return an instance with the given value, {@code isChanged == false}, and {@code isInitial == + * true} + */ + public static TrackedValue initialValue(T value) { + return new TrackedValue<>(value, false, true); + } + + /** + * Creates a tracked value representing an explicit change performed via the builder API. + * + * @param the value type + * @param value the changed value (may be {@code null}) + * @return an instance with the given value and {@code isChanged == true} + */ + public static TrackedValue changedValue(T value) { + return new TrackedValue<>(value, true, false); + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDto.java index 73bfc2a8..9f0fff49 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 @@ -26,6 +26,7 @@ import java.util.LinkedHashMap; import java.util.Map; +import java.util.Objects; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.javahelpers.codegen.model.type.TypeName; @@ -34,7 +35,8 @@ * DTO representing an annotation to be generated in the output class. Contains the annotation type * and its members in a plain format suitable for code generation. */ -public class AnnotationDto { +public class AnnotationDto implements AnnotationDtoBuilder.With { + /** The annotation type (fully qualified name). */ private TypeName annotationType; @@ -82,6 +84,18 @@ public void addMember(String name, String value) { this.members.put(name, value); } + /** + * Replaces members with the given collection; 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<>(Objects.requireNonNull(members)); + this.members.clear(); + this.members.putAll(copy); + } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java new file mode 100644 index 00000000..dc1c0d3b --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java @@ -0,0 +1,346 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.TrackedValue.unsetValue; + +import java.util.LinkedHashMap; +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 org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.HashMapBuilder; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.TrackedValue; +import org.javahelpers.codegen.model.type.TypeName; + +/** + * 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"))
+ *     .build();
+ * }
+ */ +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; + } + + /** + * Sets annotationType by class. + * + * @param annotationType the class to set as annotationType + * @return fluent {@code builder} instance + */ + public AnnotationDtoBuilder annotationType(Class annotationType) { + return annotationType(TypeName.of(annotationType)); + } + + /** + * Sets the value for annotationType from package and class name. + * + * @param packageName the package of the type + * @param className the simple name of the type + * @return current instance of builder + */ + public AnnotationDtoBuilder annotationType(String packageName, String className) { + return annotationType(new TypeName(packageName, className)); + } + + /** + * 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; + } + + /** + * Adds a single member to the annotation. + * + * @param key member name + * @param value member value + * @return this builder + */ + public AnnotationDtoBuilder add2Members(String key, String value) { + Map newMap = + this.members.isSet() ? new LinkedHashMap<>(this.members.value()) : new LinkedHashMap<>(); + newMap.put(key, value); + this.members = changedValue(newMap); + 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; + } + + /** + * 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 67fbf592..6168bb53 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 @@ -27,6 +27,7 @@ import static org.javahelpers.codegen.enums.AccessModifier.PRIVATE; import java.util.LinkedHashSet; +import java.util.Objects; import java.util.Set; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -45,7 +46,8 @@ * *

This DTO contains only rendering information for a field, consumed by the code generator. */ -public class ClassFieldDto { +public class ClassFieldDto implements ClassFieldDtoBuilder.With { + /** Field name in generated class. */ private String fieldName; @@ -163,6 +165,21 @@ public void addStaticImport(TypeName type, String memberName) { this.fieldTypeImports.add(new StaticImport(typeRaw, memberName)); } + /** + * Replaces fieldTypeImports with the given collection; 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) { + Objects.requireNonNull(fieldTypeImports); + if (fieldTypeImports != this.fieldTypeImports) { + this.fieldTypeImports.clear(); + this.fieldTypeImports.addAll(fieldTypeImports); + } + } + /** * Returns a short string representation of this field using Apache Commons ToStringBuilder. * diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java new file mode 100644 index 00000000..7711f91e --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java @@ -0,0 +1,765 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.TrackedValue.unsetValue; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.HashSetBuilder; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.TrackedValue; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.model.imports.ImportStatement; +import org.javahelpers.codegen.model.imports.RegularImport; +import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +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.TypeNameList; +import org.javahelpers.codegen.model.type.TypeNameMap; +import org.javahelpers.codegen.model.type.TypeNameSet; + +/** + * 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"))
+ *     .javadoc(new JavadocDto())
+ *     .javadoc(JavadocDto::new)
+ *     .javadoc(javadocDtoBuilder -> javadocDtoBuilder)
+ *     .literalInitializer("example literalInitializer")
+ *     .literalInitializer("Hello %s", "World")
+ *     .literalInitializer(() -> "example literalInitializer")
+ *     .literalInitializer(sb -> sb.append("text"))
+ *     .build();
+ * }
+ */ +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; + } + + /** + * 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; + } + + /** + * Sets fieldType to a TypeNameList built from the given list element type. + * + * @param elementClass the list element type + * @return fluent {@code builder} instance + */ + public ClassFieldDtoBuilder fieldTypeList(Class elementClass) { + return fieldType(TypeNameList.of(elementClass)); + } + + /** + * Sets fieldType to a TypeNameList built from the given list element type. + * + * @param elementType the list element type + * @return fluent {@code builder} instance + */ + public ClassFieldDtoBuilder fieldTypeList(TypeName elementType) { + return fieldType(TypeNameList.of(elementType)); + } + + /** + * Sets fieldType to a TypeNameSet built from the given set element type. + * + * @param elementClass the set element type + * @return fluent {@code builder} instance + */ + public ClassFieldDtoBuilder fieldTypeSet(Class elementClass) { + return fieldType(TypeNameSet.of(elementClass)); + } + + /** + * Sets fieldType to a TypeNameSet built from the given set element type. + * + * @param elementType the set element type + * @return fluent {@code builder} instance + */ + public ClassFieldDtoBuilder fieldTypeSet(TypeName elementType) { + return fieldType(TypeNameSet.of(elementType)); + } + + /** + * Sets fieldType to a TypeNameArray built from the given array component type. + * + * @param innerClass the array component type + * @return fluent {@code builder} instance + */ + public ClassFieldDtoBuilder fieldTypeArray(Class innerClass) { + return fieldType(TypeNameArray.of(innerClass)); + } + + /** + * Sets fieldType to a TypeNameArray built from the given array component type. + * + * @param innerType the array component type + * @return fluent {@code builder} instance + */ + public ClassFieldDtoBuilder fieldTypeArray(TypeName innerType) { + return fieldType(TypeNameArray.of(innerType)); + } + + /** + * Sets fieldType to a TypeNameGeneric built from the given generic outer type and + * type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public ClassFieldDtoBuilder fieldTypeGeneric(Class outerType, Class... innerTypeArguments) { + return fieldType(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets fieldType to a TypeNameGeneric built from the given generic outer type and + * type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public ClassFieldDtoBuilder fieldTypeGeneric(TypeName outerType, TypeName... innerTypeArguments) { + return fieldType(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets fieldType to a TypeNameMap built from the given map key and value types. + * + * @param keyClass the map key and value types + * @param valueClass the map key and value types + * @return fluent {@code builder} instance + */ + public ClassFieldDtoBuilder fieldTypeMap(Class keyClass, Class valueClass) { + return fieldType(TypeNameMap.of(keyClass, valueClass)); + } + + /** + * Sets fieldType to a TypeNameMap built from the given map key and value types. + * + * @param keyType the map key and value types + * @param valueType the map key and value types + * @return fluent {@code builder} instance + */ + public ClassFieldDtoBuilder fieldTypeMap(TypeName keyType, TypeName valueType) { + return fieldType(TypeNameMap.of(keyType, valueType)); + } + + /** + * Sets fieldType by class. + * + * @param fieldType the class to set as fieldType + * @return fluent {@code builder} instance + */ + public ClassFieldDtoBuilder fieldType(Class fieldType) { + return fieldType(TypeName.of(fieldType)); + } + + /** + * Sets the value for fieldType from package and class name. + * + * @param packageName the package of the type + * @param className the simple name of the type + * @return current instance of builder + */ + public ClassFieldDtoBuilder fieldType(String packageName, String className) { + return fieldType(new TypeName(packageName, className)); + } + + /** + * 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; + } + + /** + * Adds an import for the field type for the given class. + * + * @param clazz class to import + * @return this builder + */ + public ClassFieldDtoBuilder add2FieldTypeImports(Class clazz) { + return add2FieldTypeImports(new RegularImport(TypeName.of(clazz))); + } + + /** + * Adds an import for the field type for the given type. + * + * @param typeName type to import + * @return this builder + */ + public ClassFieldDtoBuilder add2FieldTypeImports(TypeName typeName) { + return add2FieldTypeImports(new RegularImport(typeName)); + } + + /** + * 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(new LinkedHashSet<>(Arrays.asList(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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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 f84636ce..6b04b0a8 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 @@ -27,6 +27,7 @@ import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; +import java.util.Objects; import java.util.Set; import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.enums.FormattingMode; @@ -51,7 +52,8 @@ *

This base class contains all information needed by the code generator to render a class, * independent of whether it's a builder, Jackson module, or other generated class type. */ -public class GenerationTargetClassDto { +public class GenerationTargetClassDto implements GenerationTargetClassDtoBuilder.With { + /** Generated class FQN. */ private TypeName typeName; @@ -131,6 +133,20 @@ public void addClassField(ClassFieldDto classField) { this.classFields.add(classField); } + /** + * Replaces classFields with the given collection; 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) { + Objects.requireNonNull(classFields); + if (classFields != this.classFields) { + this.classFields.clear(); + this.classFields.addAll(classFields); + } + } + public List getConstructors() { return constructors; } @@ -139,6 +155,20 @@ public void addConstructor(ConstructorDto constructor) { this.constructors.add(constructor); } + /** + * Replaces constructors with the given collection; 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) { + Objects.requireNonNull(constructors); + if (constructors != this.constructors) { + this.constructors.clear(); + this.constructors.addAll(constructors); + } + } + public List getMethods() { return methods; } @@ -147,6 +177,20 @@ public void addMethod(MethodDto method) { this.methods.add(method); } + /** + * Replaces methods with the given collection; 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) { + Objects.requireNonNull(methods); + if (methods != this.methods) { + this.methods.clear(); + this.methods.addAll(methods); + } + } + public Set getImports() { return imports; } @@ -205,6 +249,20 @@ public void addStaticImport(TypeName type, String memberName) { addImport(new StaticImport(typeRaw, memberName)); } + /** + * Replaces imports with the given collection; 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) { + Objects.requireNonNull(imports); + if (imports != this.imports) { + this.imports.clear(); + this.imports.addAll(imports); + } + } + /** * Adds a generic parameter definition. * @@ -214,6 +272,20 @@ public void addGeneric(GenericParameterDto generic) { generics.add(generic); } + /** + * Replaces generics with the given collection; 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) { + Objects.requireNonNull(generics); + if (generics != this.generics) { + this.generics.clear(); + this.generics.addAll(generics); + } + } + /** * Returns the list of generic parameters of the target DTO, in declared order. * @@ -242,6 +314,20 @@ public void addNestedType(NestedTypeDto nestedType) { this.nestedTypes.add(nestedType); } + /** + * Replaces nestedTypes with the given collection; 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) { + Objects.requireNonNull(nestedTypes); + if (nestedTypes != this.nestedTypes) { + this.nestedTypes.clear(); + this.nestedTypes.addAll(nestedTypes); + } + } + /** * Returns the set of class-level annotations. * @@ -260,6 +346,21 @@ public void addClassAnnotation(AnnotationDto annotation) { this.classAnnotations.add(annotation); } + /** + * Replaces classAnnotations with the given collection; 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) { + Objects.requireNonNull(classAnnotations); + if (classAnnotations != this.classAnnotations) { + this.classAnnotations.clear(); + this.classAnnotations.addAll(classAnnotations); + } + } + /** * Returns the set of interfaces to be implemented by the generated class. * @@ -278,6 +379,20 @@ public void addInterface(InterfaceName interfaceType) { this.interfaces.add(interfaceType); } + /** + * Replaces interfaces with the given collection; 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) { + Objects.requireNonNull(interfaces); + if (interfaces != this.interfaces) { + this.interfaces.clear(); + this.interfaces.addAll(interfaces); + } + } + /** * Returns the class-level JavaDoc for the generated class. * diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java new file mode 100644 index 00000000..98fd5c22 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java @@ -0,0 +1,1444 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.TrackedValue.unsetValue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.HashSetBuilder; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.TrackedValue; +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.imports.RegularImport; +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.codegen.model.type.TypeNameArray; +import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNameList; +import org.javahelpers.codegen.model.type.TypeNameMap; +import org.javahelpers.codegen.model.type.TypeNameSet; + +/** + * 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(annotationDtoBuilder -> annotationDtoBuilder)
+ *     .classAnnotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build())
+ *     .add2ClassAnnotations(AnnotationDtoBuilder.create().build())
+ *     .classFields(List.of(ClassFieldDtoBuilder.create().build()))
+ *     .classFields(() -> List.of(ClassFieldDtoBuilder.create().build()))
+ *     .classFields(classFieldDtoBuilder -> classFieldDtoBuilder)
+ *     .classFields(ClassFieldDtoBuilder.create().build(), ClassFieldDtoBuilder.create().build())
+ *     .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(constructorDtoBuilder -> constructorDtoBuilder)
+ *     .constructors(ConstructorDtoBuilder.create().build(), ConstructorDtoBuilder.create().build())
+ *     .add2Constructors(ConstructorDtoBuilder.create().build())
+ *     .generics(List.of(GenericParameterDtoBuilder.create().build()))
+ *     .generics(() -> List.of(GenericParameterDtoBuilder.create().build()))
+ *     .generics(genericParameterDtoBuilder -> genericParameterDtoBuilder)
+ *     .generics(GenericParameterDtoBuilder.create().build(), GenericParameterDtoBuilder.create().build())
+ *     .add2Generics(GenericParameterDtoBuilder.create().build())
+ *     .methods(List.of(MethodDtoBuilder.create().build()))
+ *     .methods(() -> List.of(MethodDtoBuilder.create().build()))
+ *     .methods(methodDtoBuilder -> methodDtoBuilder)
+ *     .methods(MethodDtoBuilder.create().build(), MethodDtoBuilder.create().build())
+ *     .add2Methods(MethodDtoBuilder.create().build())
+ *     .nestedTypes(List.of(NestedTypeDtoBuilder.create().build()))
+ *     .nestedTypes(() -> List.of(NestedTypeDtoBuilder.create().build()))
+ *     .nestedTypes(nestedTypeDtoBuilder -> nestedTypeDtoBuilder)
+ *     .nestedTypes(NestedTypeDtoBuilder.create().build(), NestedTypeDtoBuilder.create().build())
+ *     .add2NestedTypes(NestedTypeDtoBuilder.create().build())
+ *     .build();
+ * }
+ */ +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; + } + + /** + * 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; + } + + /** + * Adds one annotation of the given type to 2ClassAnnotations. + * + * @param annotationType the annotation type (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder add2ClassAnnotations(Class annotationType) { + return add2ClassAnnotations( + AnnotationDtoBuilder.create().annotationType(annotationType).build()); + } + + /** + * Adds one annotation of the given type to 2ClassAnnotations. + * + * @param packageName package of the annotation type + * @param className simple name of the annotation type + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder add2ClassAnnotations( + String packageName, String className) { + return add2ClassAnnotations( + AnnotationDtoBuilder.create().annotationType(packageName, className).build()); + } + + /** + * Adds one element to classAnnotations, configured through its builder. + * + * @param classAnnotationBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder classAnnotations( + Consumer classAnnotationBuilderConsumer) { + AnnotationDtoBuilder elementBuilder = AnnotationDtoBuilder.create(); + classAnnotationBuilderConsumer.accept(elementBuilder); + return add2ClassAnnotations(elementBuilder.build()); + } + + /** + * Adds elements to classAnnotations, each configured through its builder. + * + * @param classAnnotationBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final GenerationTargetClassDtoBuilder classAnnotations( + Consumer... classAnnotationBuilderConsumers) { + for (Consumer consumer : classAnnotationBuilderConsumers) { + classAnnotations(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * Adds one element to classFields, configured through its builder. + * + * @param classFieldBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder classFields( + Consumer classFieldBuilderConsumer) { + ClassFieldDtoBuilder elementBuilder = ClassFieldDtoBuilder.create(); + classFieldBuilderConsumer.accept(elementBuilder); + return add2ClassFields(elementBuilder.build()); + } + + /** + * Adds elements to classFields, each configured through its builder. + * + * @param classFieldBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final GenerationTargetClassDtoBuilder classFields( + Consumer... classFieldBuilderConsumers) { + for (Consumer consumer : classFieldBuilderConsumers) { + classFields(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * Adds one element to constructors, configured through its builder. + * + * @param constructorBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder constructors( + Consumer constructorBuilderConsumer) { + ConstructorDtoBuilder elementBuilder = ConstructorDtoBuilder.create(); + constructorBuilderConsumer.accept(elementBuilder); + return add2Constructors(elementBuilder.build()); + } + + /** + * Adds elements to constructors, each configured through its builder. + * + * @param constructorBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final GenerationTargetClassDtoBuilder constructors( + Consumer... constructorBuilderConsumers) { + for (Consumer consumer : constructorBuilderConsumers) { + constructors(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * Adds one element to generics, configured through its builder. + * + * @param genericBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder generics( + Consumer genericBuilderConsumer) { + GenericParameterDtoBuilder elementBuilder = GenericParameterDtoBuilder.create(); + genericBuilderConsumer.accept(elementBuilder); + return add2Generics(elementBuilder.build()); + } + + /** + * Adds elements to generics, each configured through its builder. + * + * @param genericBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final GenerationTargetClassDtoBuilder generics( + Consumer... genericBuilderConsumers) { + for (Consumer consumer : genericBuilderConsumers) { + generics(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * Adds an import for the given class. + * + * @param clazz class to import + * @return this builder + */ + public GenerationTargetClassDtoBuilder add2Imports(Class clazz) { + return add2Imports(new RegularImport(TypeName.of(clazz))); + } + + /** + * Adds an import for the given type. + * + * @param typeName type to import + * @return this builder + */ + public GenerationTargetClassDtoBuilder add2Imports(TypeName typeName) { + return add2Imports(new RegularImport(typeName)); + } + + /** + * 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(new LinkedHashSet<>(Arrays.asList(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; + } + + /** + * 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(new LinkedHashSet<>(Arrays.asList(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; + } + + /** + * 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; + } + + /** + * Adds one element to methods, configured through its builder. + * + * @param methodBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder methods(Consumer methodBuilderConsumer) { + MethodDtoBuilder elementBuilder = MethodDtoBuilder.create(); + methodBuilderConsumer.accept(elementBuilder); + return add2Methods(elementBuilder.build()); + } + + /** + * Adds elements to methods, each configured through its builder. + * + * @param methodBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final GenerationTargetClassDtoBuilder methods( + Consumer... methodBuilderConsumers) { + for (Consumer consumer : methodBuilderConsumers) { + methods(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * Adds one element to nestedTypes, configured through its builder. + * + * @param nestedTypeBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder nestedTypes( + Consumer nestedTypeBuilderConsumer) { + NestedTypeDtoBuilder elementBuilder = NestedTypeDtoBuilder.create(); + nestedTypeBuilderConsumer.accept(elementBuilder); + return add2NestedTypes(elementBuilder.build()); + } + + /** + * Adds elements to nestedTypes, each configured through its builder. + * + * @param nestedTypeBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final GenerationTargetClassDtoBuilder nestedTypes( + Consumer... nestedTypeBuilderConsumers) { + for (Consumer consumer : nestedTypeBuilderConsumers) { + nestedTypes(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * Sets superType to a TypeNameList built from the given list element type. + * + * @param elementClass the list element type + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder superTypeList(Class elementClass) { + return superType(TypeNameList.of(elementClass)); + } + + /** + * Sets superType to a TypeNameList built from the given list element type. + * + * @param elementType the list element type + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder superTypeList(TypeName elementType) { + return superType(TypeNameList.of(elementType)); + } + + /** + * Sets superType to a TypeNameSet built from the given set element type. + * + * @param elementClass the set element type + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder superTypeSet(Class elementClass) { + return superType(TypeNameSet.of(elementClass)); + } + + /** + * Sets superType to a TypeNameSet built from the given set element type. + * + * @param elementType the set element type + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder superTypeSet(TypeName elementType) { + return superType(TypeNameSet.of(elementType)); + } + + /** + * Sets superType to a TypeNameArray built from the given array component type. + * + * @param innerClass the array component type + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder superTypeArray(Class innerClass) { + return superType(TypeNameArray.of(innerClass)); + } + + /** + * Sets superType to a TypeNameArray built from the given array component type. + * + * @param innerType the array component type + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder superTypeArray(TypeName innerType) { + return superType(TypeNameArray.of(innerType)); + } + + /** + * Sets superType to a TypeNameGeneric built from the given generic outer type and + * type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder superTypeGeneric( + Class outerType, Class... innerTypeArguments) { + return superType(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets superType to a TypeNameGeneric built from the given generic outer type and + * type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder superTypeGeneric( + TypeName outerType, TypeName... innerTypeArguments) { + return superType(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets superType to a TypeNameMap built from the given map key and value types. + * + * @param keyClass the map key and value types + * @param valueClass the map key and value types + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder superTypeMap(Class keyClass, Class valueClass) { + return superType(TypeNameMap.of(keyClass, valueClass)); + } + + /** + * Sets superType to a TypeNameMap built from the given map key and value types. + * + * @param keyType the map key and value types + * @param valueType the map key and value types + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder superTypeMap(TypeName keyType, TypeName valueType) { + return superType(TypeNameMap.of(keyType, valueType)); + } + + /** + * Sets superType by class. + * + * @param superType the class to set as superType + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder superType(Class superType) { + return superType(TypeName.of(superType)); + } + + /** + * Sets the value for superType from package and class name. + * + * @param packageName the package of the type + * @param className the simple name of the type + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder superType(String packageName, String className) { + return superType(new TypeName(packageName, className)); + } + + /** + * 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; + } + + /** + * Sets typeName by class. + * + * @param typeName the class to set as typeName + * @return fluent {@code builder} instance + */ + public GenerationTargetClassDtoBuilder typeName(Class typeName) { + return typeName(TypeName.of(typeName)); + } + + /** + * Sets the value for typeName from package and class name. + * + * @param packageName the package of the type + * @param className the simple name of the type + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder typeName(String packageName, String className) { + return typeName(new TypeName(packageName, className)); + } + + /** + * 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/JavadocCodeBlockDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDto.java index ad694b80..6889bef8 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDto.java @@ -33,6 +33,7 @@ * examples that appear in Javadoc comments. This allows generators to create code examples with * placeholders that are resolved during code generation. */ -public class JavadocCodeBlockDto extends CodeTemplateDto { +public class JavadocCodeBlockDto extends CodeTemplateDto + implements JavadocCodeBlockDtoBuilder.With { // All functionality inherited from CodeTemplateDto } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java new file mode 100644 index 00000000..0fe0fb70 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java @@ -0,0 +1,491 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.TrackedValue.unsetValue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.ArrayListBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.HashSetBuilder; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.TrackedValue; +import org.javahelpers.codegen.model.imports.ImportStatement; +import org.javahelpers.codegen.model.imports.RegularImport; +import org.javahelpers.codegen.model.method.MethodCodePlaceholder; +import org.javahelpers.codegen.model.type.TypeName; + +/** + * Builder for {@code org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDto}. + * + *

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

Example:

+ * + *
{@code
+ * JavadocCodeBlockDto result = JavadocCodeBlockDtoBuilder.create()
+ *     .codeFormat("example codeFormat")
+ *     .codeFormat("Hello %s", "World")
+ *     .codeFormat(() -> "example codeFormat")
+ *     .codeFormat(sb -> sb.append("text"))
+ *     .build();
+ * }
+ */ +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; + } + + /** + * 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; + } + + /** + * Adds a code block import for the given class. + * + * @param clazz class to import + * @return this builder + */ + public JavadocCodeBlockDtoBuilder add2CodeBlockImports(Class clazz) { + return add2CodeBlockImports(new RegularImport(TypeName.of(clazz))); + } + + /** + * Adds a code block import for the given type. + * + * @param typeName type to import + * @return this builder + */ + public JavadocCodeBlockDtoBuilder add2CodeBlockImports(TypeName typeName) { + return add2CodeBlockImports(new RegularImport(typeName)); + } + + /** + * 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(new LinkedHashSet<>(Arrays.asList(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; + } + + /** + * 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; + } + + /** + * 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 51cb2224..ade33be6 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 @@ -45,7 +45,7 @@ * .addReturn("a new PersonDto instance"); * } */ -public class JavadocDto { +public class JavadocDto implements JavadocDtoBuilder.With { /** The main description text (everything before the first tag). */ private String description; @@ -160,6 +160,20 @@ public void addTag(String tagName) { } } + /** + * Replaces tags with the given collection; 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) { + Objects.requireNonNull(tags); + if (tags != this.tags) { + this.tags.clear(); + this.tags.addAll(tags); + } + } + /** * Adds a @param tag with optional formatted 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 00000000..428be267 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDtoBuilder.java @@ -0,0 +1,507 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.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 org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.ArrayListBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.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"))
+ *     .exampleUsageCodeBlock(new JavadocCodeBlockDto())
+ *     .exampleUsageCodeBlock(JavadocCodeBlockDto::new)
+ *     .exampleUsageCodeBlock(javadocCodeBlockDtoBuilder -> javadocCodeBlockDtoBuilder)
+ *     .build();
+ * }
+ */ +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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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 2b45684b..4e8e60a0 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 @@ -28,6 +28,7 @@ import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; +import java.util.Objects; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.javahelpers.codegen.model.imports.ImportStatement; @@ -46,6 +47,7 @@ * code generation. */ public class CodeTemplateDto { + /** Format of code. Holding placeholder for dynamic values. */ private String codeFormat; @@ -108,6 +110,18 @@ public void addCodeArgument(MethodCodePlaceholder placeholder) { codeArguments.add(placeholder); } + /** + * Replaces codeArguments with the given collection; 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<>(Objects.requireNonNull(codeArguments)); + this.codeArguments.clear(); + this.codeArguments.addAll(copy); + } + /** * Checks if this code DTO has code content. * @@ -163,6 +177,21 @@ public void addStaticImport(Class clazz, String memberName) { this.codeBlockImports.add(new StaticImport(TypeName.of(clazz), memberName)); } + /** + * Replaces codeBlockImports with the given collection; 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) { + Objects.requireNonNull(codeBlockImports); + if (codeBlockImports != this.codeBlockImports) { + this.codeBlockImports.clear(); + this.codeBlockImports.addAll(codeBlockImports); + } + } + /** * Adds type imports for a TypeName and its generic type arguments (convenience method). * diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java new file mode 100644 index 00000000..5e0c0928 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java @@ -0,0 +1,489 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.TrackedValue.unsetValue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.ArrayListBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.HashSetBuilder; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.TrackedValue; +import org.javahelpers.codegen.model.imports.ImportStatement; +import org.javahelpers.codegen.model.imports.RegularImport; +import org.javahelpers.codegen.model.type.TypeName; + +/** + * Builder for {@code org.javahelpers.codegen.model.method.CodeTemplateDto}. + * + *

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

Example:

+ * + *
{@code
+ * CodeTemplateDto result = CodeTemplateDtoBuilder.create()
+ *     .codeFormat("example codeFormat")
+ *     .codeFormat("Hello %s", "World")
+ *     .codeFormat(() -> "example codeFormat")
+ *     .codeFormat(sb -> sb.append("text"))
+ *     .build();
+ * }
+ */ +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; + } + + /** + * 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; + } + + /** + * Adds a code block import for the given class. + * + * @param clazz class to import + * @return this builder + */ + public CodeTemplateDtoBuilder add2CodeBlockImports(Class clazz) { + return add2CodeBlockImports(new RegularImport(TypeName.of(clazz))); + } + + /** + * Adds a code block import for the given type. + * + * @param typeName type to import + * @return this builder + */ + public CodeTemplateDtoBuilder add2CodeBlockImports(TypeName typeName) { + return add2CodeBlockImports(new RegularImport(typeName)); + } + + /** + * 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(new LinkedHashSet<>(Arrays.asList(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; + } + + /** + * 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; + } + + /** + * 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 936d453f..15920757 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 @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.LinkedList; import java.util.List; +import java.util.Objects; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.javahelpers.codegen.enums.AccessModifier; @@ -38,7 +39,8 @@ * *

This DTO contains all information needed to render a constructor in the generated class. */ -public class ConstructorDto { +public class ConstructorDto implements ConstructorDtoBuilder.With { + /** Constructor parameters. */ private final LinkedList parameters = new LinkedList<>(); @@ -62,6 +64,20 @@ public void addParameter(MethodParameterDto parameter) { this.parameters.add(parameter); } + /** + * Replaces parameters with the given collection; 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) { + Objects.requireNonNull(parameters); + if (parameters != this.parameters) { + this.parameters.clear(); + this.parameters.addAll(parameters); + } + } + /** * Gets the constructor body as MethodCodeDto. * @@ -113,6 +129,20 @@ public void addAnnotation(AnnotationDto annotation) { this.annotations.add(annotation); } + /** + * Replaces annotations with the given collection; 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) { + Objects.requireNonNull(annotations); + if (annotations != this.annotations) { + this.annotations.clear(); + this.annotations.addAll(annotations); + } + } + /** * Returns a string representation of this constructor using Apache Commons ToStringBuilder. * diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java new file mode 100644 index 00000000..035eae1d --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java @@ -0,0 +1,605 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.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 org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.TrackedValue; +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; + +/** + * 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(annotationDtoBuilder -> annotationDtoBuilder)
+ *     .annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build())
+ *     .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(methodParameterDtoBuilder -> methodParameterDtoBuilder)
+ *     .parameters(MethodParameterDtoBuilder.create().build(), MethodParameterDtoBuilder.create().build())
+ *     .add2Parameters(MethodParameterDtoBuilder.create().build())
+ *     .build();
+ * }
+ */ +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; + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param annotationType the annotation type (not null) + * @return current instance of builder + */ + public ConstructorDtoBuilder add2Annotations(Class annotationType) { + return add2Annotations(AnnotationDtoBuilder.create().annotationType(annotationType).build()); + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param packageName package of the annotation type + * @param className simple name of the annotation type + * @return current instance of builder + */ + public ConstructorDtoBuilder add2Annotations(String packageName, String className) { + return add2Annotations( + AnnotationDtoBuilder.create().annotationType(packageName, className).build()); + } + + /** + * Adds one element to annotations, configured through its builder. + * + * @param annotationBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public ConstructorDtoBuilder annotations( + Consumer annotationBuilderConsumer) { + AnnotationDtoBuilder elementBuilder = AnnotationDtoBuilder.create(); + annotationBuilderConsumer.accept(elementBuilder); + return add2Annotations(elementBuilder.build()); + } + + /** + * Adds elements to annotations, each configured through its builder. + * + * @param annotationBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final ConstructorDtoBuilder annotations( + Consumer... annotationBuilderConsumers) { + for (Consumer consumer : annotationBuilderConsumers) { + annotations(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * Adds one element to parameters, configured through its builder. + * + * @param parameterBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public ConstructorDtoBuilder parameters( + Consumer parameterBuilderConsumer) { + MethodParameterDtoBuilder elementBuilder = MethodParameterDtoBuilder.create(); + parameterBuilderConsumer.accept(elementBuilder); + return add2Parameters(elementBuilder.build()); + } + + /** + * Adds elements to parameters, each configured through its builder. + * + * @param parameterBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final ConstructorDtoBuilder parameters( + Consumer... parameterBuilderConsumers) { + for (Consumer consumer : parameterBuilderConsumers) { + parameters(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * 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/MethodCodeDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDto.java index 3a243a47..b240e750 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDto.java @@ -25,6 +25,6 @@ package org.javahelpers.codegen.model.method; /** DTO for holding information of code implementation. */ -public class MethodCodeDto extends CodeTemplateDto { +public class MethodCodeDto extends CodeTemplateDto implements MethodCodeDtoBuilder.With { // All functionality inherited from CodeTemplateDto } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java new file mode 100644 index 00000000..2d5cfc8f --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java @@ -0,0 +1,488 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.TrackedValue.unsetValue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.ArrayListBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.HashSetBuilder; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.TrackedValue; +import org.javahelpers.codegen.model.imports.ImportStatement; +import org.javahelpers.codegen.model.imports.RegularImport; +import org.javahelpers.codegen.model.type.TypeName; + +/** + * Builder for {@code org.javahelpers.codegen.model.method.MethodCodeDto}. + * + *

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

Example:

+ * + *
{@code
+ * MethodCodeDto result = MethodCodeDtoBuilder.create()
+ *     .codeFormat("example codeFormat")
+ *     .codeFormat("Hello %s", "World")
+ *     .codeFormat(() -> "example codeFormat")
+ *     .codeFormat(sb -> sb.append("text"))
+ *     .build();
+ * }
+ */ +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; + } + + /** + * 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; + } + + /** + * Adds a code block import for the given class. + * + * @param clazz class to import + * @return this builder + */ + public MethodCodeDtoBuilder add2CodeBlockImports(Class clazz) { + return add2CodeBlockImports(new RegularImport(TypeName.of(clazz))); + } + + /** + * Adds a code block import for the given type. + * + * @param typeName type to import + * @return this builder + */ + public MethodCodeDtoBuilder add2CodeBlockImports(TypeName typeName) { + return add2CodeBlockImports(new RegularImport(typeName)); + } + + /** + * 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(new LinkedHashSet<>(Arrays.asList(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; + } + + /** + * 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; + } + + /** + * 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 cb6c456a..f2d68ebe 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; @@ -43,7 +44,8 @@ * holds only rendering-relevant data — no field-origin metadata or other generation-phase-only * information. */ -public class MethodDto { +public class MethodDto implements MethodDtoBuilder.With { + /** Access modifier for method. */ private Optional modifier = Optional.empty(); @@ -126,6 +128,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. * @@ -162,6 +177,20 @@ public void addParameter(MethodParameterDto paramDto) { this.parameters.add(paramDto); } + /** + * Replaces parameters with the given collection; 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) { + Objects.requireNonNull(parameters); + if (parameters != this.parameters) { + this.parameters.clear(); + this.parameters.addAll(parameters); + } + } + /** * Getting a list of parameters of method. * @@ -180,6 +209,21 @@ public void addGenericParameter(GenericParameterDto genericParameter) { this.genericParameters.add(genericParameter); } + /** + * Replaces genericParameters with the given collection; 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) { + Objects.requireNonNull(genericParameters); + if (genericParameters != this.genericParameters) { + this.genericParameters.clear(); + this.genericParameters.addAll(genericParameters); + } + } + /** * Getting a list of generic type parameters of method. * @@ -297,6 +341,20 @@ public void addAnnotation(AnnotationDto annotation) { this.annotations.add(annotation); } + /** + * Replaces annotations with the given collection; 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) { + Objects.requireNonNull(annotations); + if (annotations != this.annotations) { + this.annotations.clear(); + this.annotations.addAll(annotations); + } + } + /** * Returns a string representation of this method in Java method signature format. * diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java new file mode 100644 index 00000000..2371bbe2 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java @@ -0,0 +1,1110 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.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 org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.TrackedValue; +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.codegen.model.type.TypeNameArray; +import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNameList; +import org.javahelpers.codegen.model.type.TypeNameMap; +import org.javahelpers.codegen.model.type.TypeNameSet; + +/** + * 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"))
+ *     .annotations(List.of(AnnotationDtoBuilder.create().build()))
+ *     .annotations(() -> List.of(AnnotationDtoBuilder.create().build()))
+ *     .annotations(annotationDtoBuilder -> annotationDtoBuilder)
+ *     .annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build())
+ *     .add2Annotations(AnnotationDtoBuilder.create().build())
+ *     .code("example code")
+ *     .code("Hello %s", "World")
+ *     .code(() -> "example code")
+ *     .code(sb -> sb.append("text"))
+ *     .genericParameters(List.of(GenericParameterDtoBuilder.create().build()))
+ *     .genericParameters(() -> List.of(GenericParameterDtoBuilder.create().build()))
+ *     .genericParameters(genericParameterDtoBuilder -> genericParameterDtoBuilder)
+ *     .genericParameters(GenericParameterDtoBuilder.create().build(), GenericParameterDtoBuilder.create().build())
+ *     .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(methodParameterDtoBuilder -> methodParameterDtoBuilder)
+ *     .parameters(MethodParameterDtoBuilder.create().build(), MethodParameterDtoBuilder.create().build())
+ *     .add2Parameters(MethodParameterDtoBuilder.create().build())
+ *     .isStatic(true)
+ *     .isStatic(() -> true)
+ *     .build();
+ * }
+ */ +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; + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param annotationType the annotation type (not null) + * @return current instance of builder + */ + public MethodDtoBuilder add2Annotations(Class annotationType) { + return add2Annotations(AnnotationDtoBuilder.create().annotationType(annotationType).build()); + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param packageName package of the annotation type + * @param className simple name of the annotation type + * @return current instance of builder + */ + public MethodDtoBuilder add2Annotations(String packageName, String className) { + return add2Annotations( + AnnotationDtoBuilder.create().annotationType(packageName, className).build()); + } + + /** + * Adds one element to annotations, configured through its builder. + * + * @param annotationBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public MethodDtoBuilder annotations(Consumer annotationBuilderConsumer) { + AnnotationDtoBuilder elementBuilder = AnnotationDtoBuilder.create(); + annotationBuilderConsumer.accept(elementBuilder); + return add2Annotations(elementBuilder.build()); + } + + /** + * Adds elements to annotations, each configured through its builder. + * + * @param annotationBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final MethodDtoBuilder annotations( + Consumer... annotationBuilderConsumers) { + for (Consumer consumer : annotationBuilderConsumers) { + annotations(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * Adds one element to genericParameters, configured through its builder. + * + * @param genericParameterBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public MethodDtoBuilder genericParameters( + Consumer genericParameterBuilderConsumer) { + GenericParameterDtoBuilder elementBuilder = GenericParameterDtoBuilder.create(); + genericParameterBuilderConsumer.accept(elementBuilder); + return add2GenericParameters(elementBuilder.build()); + } + + /** + * Adds elements to genericParameters, each configured through its builder. + * + * @param genericParameterBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final MethodDtoBuilder genericParameters( + Consumer... genericParameterBuilderConsumers) { + for (Consumer consumer : genericParameterBuilderConsumers) { + genericParameters(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * Adds one element to parameters, configured through its builder. + * + * @param parameterBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public MethodDtoBuilder parameters(Consumer parameterBuilderConsumer) { + MethodParameterDtoBuilder elementBuilder = MethodParameterDtoBuilder.create(); + parameterBuilderConsumer.accept(elementBuilder); + return add2Parameters(elementBuilder.build()); + } + + /** + * Adds elements to parameters, each configured through its builder. + * + * @param parameterBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final MethodDtoBuilder parameters( + Consumer... parameterBuilderConsumers) { + for (Consumer consumer : parameterBuilderConsumers) { + parameters(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * Sets returnType to a TypeNameList built from the given list element type. + * + * @param elementClass the list element type + * @return fluent {@code builder} instance + */ + public MethodDtoBuilder returnTypeList(Class elementClass) { + return returnType(TypeNameList.of(elementClass)); + } + + /** + * Sets returnType to a TypeNameList built from the given list element type. + * + * @param elementType the list element type + * @return fluent {@code builder} instance + */ + public MethodDtoBuilder returnTypeList(TypeName elementType) { + return returnType(TypeNameList.of(elementType)); + } + + /** + * Sets returnType to a TypeNameSet built from the given set element type. + * + * @param elementClass the set element type + * @return fluent {@code builder} instance + */ + public MethodDtoBuilder returnTypeSet(Class elementClass) { + return returnType(TypeNameSet.of(elementClass)); + } + + /** + * Sets returnType to a TypeNameSet built from the given set element type. + * + * @param elementType the set element type + * @return fluent {@code builder} instance + */ + public MethodDtoBuilder returnTypeSet(TypeName elementType) { + return returnType(TypeNameSet.of(elementType)); + } + + /** + * Sets returnType to a TypeNameArray built from the given array component type. + * + * @param innerClass the array component type + * @return fluent {@code builder} instance + */ + public MethodDtoBuilder returnTypeArray(Class innerClass) { + return returnType(TypeNameArray.of(innerClass)); + } + + /** + * Sets returnType to a TypeNameArray built from the given array component type. + * + * @param innerType the array component type + * @return fluent {@code builder} instance + */ + public MethodDtoBuilder returnTypeArray(TypeName innerType) { + return returnType(TypeNameArray.of(innerType)); + } + + /** + * Sets returnType to a TypeNameGeneric built from the given generic outer type and + * type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public MethodDtoBuilder returnTypeGeneric(Class outerType, Class... innerTypeArguments) { + return returnType(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets returnType to a TypeNameGeneric built from the given generic outer type and + * type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public MethodDtoBuilder returnTypeGeneric(TypeName outerType, TypeName... innerTypeArguments) { + return returnType(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets returnType to a TypeNameMap built from the given map key and value types. + * + * @param keyClass the map key and value types + * @param valueClass the map key and value types + * @return fluent {@code builder} instance + */ + public MethodDtoBuilder returnTypeMap(Class keyClass, Class valueClass) { + return returnType(TypeNameMap.of(keyClass, valueClass)); + } + + /** + * Sets returnType to a TypeNameMap built from the given map key and value types. + * + * @param keyType the map key and value types + * @param valueType the map key and value types + * @return fluent {@code builder} instance + */ + public MethodDtoBuilder returnTypeMap(TypeName keyType, TypeName valueType) { + return returnType(TypeNameMap.of(keyType, valueType)); + } + + /** + * Sets returnType by class. + * + * @param returnType the class to set as returnType + * @return fluent {@code builder} instance + */ + public MethodDtoBuilder returnType(Class returnType) { + return returnType(TypeName.of(returnType)); + } + + /** + * Sets the value for returnType from package and class name. + * + * @param packageName the package of the type + * @param className the simple name of the type + * @return current instance of builder + */ + public MethodDtoBuilder returnType(String packageName, String className) { + return returnType(new TypeName(packageName, className)); + } + + /** + * 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 dcd3d669..d895e901 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 @@ -26,11 +26,13 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; import org.javahelpers.codegen.model.annotation.AnnotationDto; import org.javahelpers.codegen.model.type.TypeName; /** MethodParameterDto contains all information for generating parameters in method headers. */ -public class MethodParameterDto { +public class MethodParameterDto implements MethodParameterDtoBuilder.With { + /** Name of parameter. */ private String parameterName; @@ -93,4 +95,18 @@ public List getAnnotations() { public void addAnnotation(AnnotationDto annotation) { this.annotations.add(annotation); } + + /** + * Replaces annotations with the given collection; 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) { + Objects.requireNonNull(annotations); + if (annotations != this.annotations) { + this.annotations.clear(); + this.annotations.addAll(annotations); + } + } } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java new file mode 100644 index 00000000..95f23881 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java @@ -0,0 +1,580 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.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 org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.TrackedValue; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; +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.TypeNameList; +import org.javahelpers.codegen.model.type.TypeNameMap; +import org.javahelpers.codegen.model.type.TypeNameSet; + +/** + * 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(annotationDtoBuilder -> annotationDtoBuilder)
+ *     .annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build())
+ *     .add2Annotations(AnnotationDtoBuilder.create().build())
+ *     .parameterName("example parameterName")
+ *     .parameterName("Hello %s", "World")
+ *     .parameterName(() -> "example parameterName")
+ *     .parameterName(sb -> sb.append("text"))
+ *     .build();
+ * }
+ */ +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; + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param annotationType the annotation type (not null) + * @return current instance of builder + */ + public MethodParameterDtoBuilder add2Annotations(Class annotationType) { + return add2Annotations(AnnotationDtoBuilder.create().annotationType(annotationType).build()); + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param packageName package of the annotation type + * @param className simple name of the annotation type + * @return current instance of builder + */ + public MethodParameterDtoBuilder add2Annotations(String packageName, String className) { + return add2Annotations( + AnnotationDtoBuilder.create().annotationType(packageName, className).build()); + } + + /** + * Adds one element to annotations, configured through its builder. + * + * @param annotationBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public MethodParameterDtoBuilder annotations( + Consumer annotationBuilderConsumer) { + AnnotationDtoBuilder elementBuilder = AnnotationDtoBuilder.create(); + annotationBuilderConsumer.accept(elementBuilder); + return add2Annotations(elementBuilder.build()); + } + + /** + * Adds elements to annotations, each configured through its builder. + * + * @param annotationBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final MethodParameterDtoBuilder annotations( + Consumer... annotationBuilderConsumers) { + for (Consumer consumer : annotationBuilderConsumers) { + annotations(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * Sets parameterTypeName to a TypeNameList built from the given list element type. + * + * @param elementClass the list element type + * @return fluent {@code builder} instance + */ + public MethodParameterDtoBuilder parameterTypeNameList(Class elementClass) { + return parameterTypeName(TypeNameList.of(elementClass)); + } + + /** + * Sets parameterTypeName to a TypeNameList built from the given list element type. + * + * @param elementType the list element type + * @return fluent {@code builder} instance + */ + public MethodParameterDtoBuilder parameterTypeNameList(TypeName elementType) { + return parameterTypeName(TypeNameList.of(elementType)); + } + + /** + * Sets parameterTypeName to a TypeNameSet built from the given set element type. + * + * @param elementClass the set element type + * @return fluent {@code builder} instance + */ + public MethodParameterDtoBuilder parameterTypeNameSet(Class elementClass) { + return parameterTypeName(TypeNameSet.of(elementClass)); + } + + /** + * Sets parameterTypeName to a TypeNameSet built from the given set element type. + * + * @param elementType the set element type + * @return fluent {@code builder} instance + */ + public MethodParameterDtoBuilder parameterTypeNameSet(TypeName elementType) { + return parameterTypeName(TypeNameSet.of(elementType)); + } + + /** + * Sets parameterTypeName to a TypeNameArray built from the given array component + * type. + * + * @param innerClass the array component type + * @return fluent {@code builder} instance + */ + public MethodParameterDtoBuilder parameterTypeNameArray(Class innerClass) { + return parameterTypeName(TypeNameArray.of(innerClass)); + } + + /** + * Sets parameterTypeName to a TypeNameArray built from the given array component + * type. + * + * @param innerType the array component type + * @return fluent {@code builder} instance + */ + public MethodParameterDtoBuilder parameterTypeNameArray(TypeName innerType) { + return parameterTypeName(TypeNameArray.of(innerType)); + } + + /** + * Sets parameterTypeName to a TypeNameGeneric built from the given generic outer + * type and type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public MethodParameterDtoBuilder parameterTypeNameGeneric( + Class outerType, Class... innerTypeArguments) { + return parameterTypeName(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets parameterTypeName to a TypeNameGeneric built from the given generic outer + * type and type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public MethodParameterDtoBuilder parameterTypeNameGeneric( + TypeName outerType, TypeName... innerTypeArguments) { + return parameterTypeName(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets parameterTypeName to a TypeNameMap built from the given map key and value + * types. + * + * @param keyClass the map key and value types + * @param valueClass the map key and value types + * @return fluent {@code builder} instance + */ + public MethodParameterDtoBuilder parameterTypeNameMap(Class keyClass, Class valueClass) { + return parameterTypeName(TypeNameMap.of(keyClass, valueClass)); + } + + /** + * Sets parameterTypeName to a TypeNameMap built from the given map key and value + * types. + * + * @param keyType the map key and value types + * @param valueType the map key and value types + * @return fluent {@code builder} instance + */ + public MethodParameterDtoBuilder parameterTypeNameMap(TypeName keyType, TypeName valueType) { + return parameterTypeName(TypeNameMap.of(keyType, valueType)); + } + + /** + * Sets parameterTypeName by class. + * + * @param parameterTypeName the class to set as parameterTypeName + * @return fluent {@code builder} instance + */ + public MethodParameterDtoBuilder parameterTypeName(Class parameterTypeName) { + return parameterTypeName(TypeName.of(parameterTypeName)); + } + + /** + * Sets the value for parameterTypeName from package and class name. + * + * @param packageName the package of the type + * @param className the simple name of the type + * @return current instance of builder + */ + public MethodParameterDtoBuilder parameterTypeName(String packageName, String className) { + return parameterTypeName(new TypeName(packageName, className)); + } + + /** + * 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 d6b4565a..5ad52b00 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 @@ -26,9 +26,11 @@ import java.util.LinkedList; import java.util.List; +import java.util.Objects; /** Represents a generic type parameter (e.g., {@code T extends Number & Comparable}). */ -public class GenericParameterDto { +public class GenericParameterDto implements GenericParameterDtoBuilder.With { + /** The name of the generic parameter (e.g., "T"). */ private String name; @@ -64,6 +66,20 @@ public void addUpperBound(TypeName bound) { } } + /** + * Replaces upperBounds with the given collection; 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) { + Objects.requireNonNull(upperBounds); + if (upperBounds != this.upperBounds) { + this.upperBounds.clear(); + this.upperBounds.addAll(upperBounds); + } + } + /** * Returns all upper bounds (possibly empty). * diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java new file mode 100644 index 00000000..cc7c8183 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java @@ -0,0 +1,485 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.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 org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.ArrayListBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.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"))
+ *     .build();
+ * }
+ */ +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; + } + + /** + * 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 add2UpperBounds to a TypeNameList built from the given list element type. + * + * @param elementClass the list element type + * @return fluent {@code builder} instance + */ + public GenericParameterDtoBuilder add2UpperBoundsList(Class elementClass) { + return add2UpperBounds(TypeNameList.of(elementClass)); + } + + /** + * Sets add2UpperBounds to a TypeNameList built from the given list element type. + * + * @param elementType the list element type + * @return fluent {@code builder} instance + */ + public GenericParameterDtoBuilder add2UpperBoundsList(TypeName elementType) { + return add2UpperBounds(TypeNameList.of(elementType)); + } + + /** + * Sets add2UpperBounds to a TypeNameSet built from the given set element type. + * + * @param elementClass the set element type + * @return fluent {@code builder} instance + */ + public GenericParameterDtoBuilder add2UpperBoundsSet(Class elementClass) { + return add2UpperBounds(TypeNameSet.of(elementClass)); + } + + /** + * Sets add2UpperBounds to a TypeNameSet built from the given set element type. + * + * @param elementType the set element type + * @return fluent {@code builder} instance + */ + public GenericParameterDtoBuilder add2UpperBoundsSet(TypeName elementType) { + return add2UpperBounds(TypeNameSet.of(elementType)); + } + + /** + * Sets add2UpperBounds to a TypeNameArray built from the given array component type. + * + * @param innerClass the array component type + * @return fluent {@code builder} instance + */ + public GenericParameterDtoBuilder add2UpperBoundsArray(Class innerClass) { + return add2UpperBounds(TypeNameArray.of(innerClass)); + } + + /** + * Sets add2UpperBounds to a TypeNameArray built from the given array component type. + * + * @param innerType the array component type + * @return fluent {@code builder} instance + */ + public GenericParameterDtoBuilder add2UpperBoundsArray(TypeName innerType) { + return add2UpperBounds(TypeNameArray.of(innerType)); + } + + /** + * Sets add2UpperBounds to a TypeNameGeneric built from the given generic outer type + * and type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public GenericParameterDtoBuilder add2UpperBoundsGeneric( + Class outerType, Class... innerTypeArguments) { + return add2UpperBounds(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets add2UpperBounds to a TypeNameGeneric built from the given generic outer type + * and type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public GenericParameterDtoBuilder add2UpperBoundsGeneric( + TypeName outerType, TypeName... innerTypeArguments) { + return add2UpperBounds(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets add2UpperBounds to a TypeNameMap built from the given map key and value + * types. + * + * @param keyClass the map key and value types + * @param valueClass the map key and value types + * @return fluent {@code builder} instance + */ + public GenericParameterDtoBuilder add2UpperBoundsMap(Class keyClass, Class valueClass) { + return add2UpperBounds(TypeNameMap.of(keyClass, valueClass)); + } + + /** + * Sets add2UpperBounds to a TypeNameMap built from the given map key and value + * types. + * + * @param keyType the map key and value types + * @param valueType the map key and value types + * @return fluent {@code builder} instance + */ + public GenericParameterDtoBuilder add2UpperBoundsMap(TypeName keyType, TypeName valueType) { + return add2UpperBounds(TypeNameMap.of(keyType, valueType)); + } + + /** + * Sets add2UpperBounds by class. + * + * @param element the class to set as add2UpperBounds + * @return fluent {@code builder} instance + */ + public GenericParameterDtoBuilder add2UpperBounds(Class element) { + return add2UpperBounds(TypeName.of(element)); + } + + /** + * 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; + } + + /** + * 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 e2e15cb9..72b8e13e 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 @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.LinkedList; import java.util.List; +import java.util.Objects; import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.model.annotation.AnnotationDto; import org.javahelpers.codegen.model.javadoc.JavadocDto; @@ -41,7 +42,7 @@ * *

For example, the "With" interface that allows DTOs to implement fluent modification methods. */ -public class NestedTypeDto { +public class NestedTypeDto implements NestedTypeDtoBuilder.With { /** The simple name of the nested type (e.g., "With"). */ private String typeName; @@ -98,6 +99,20 @@ public void addMethod(MethodDto method) { this.methods.add(method); } + /** + * Replaces methods with the given collection; 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) { + Objects.requireNonNull(methods); + if (methods != this.methods) { + this.methods.clear(); + this.methods.addAll(methods); + } + } + public JavadocDto getJavadoc() { return javadoc; } @@ -113,4 +128,18 @@ public List getAnnotations() { public void addAnnotation(AnnotationDto annotation) { this.annotations.add(annotation); } + + /** + * Replaces annotations with the given collection; 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) { + Objects.requireNonNull(annotations); + if (annotations != this.annotations) { + this.annotations.clear(); + this.annotations.addAll(annotations); + } + } } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java new file mode 100644 index 00000000..459f51f6 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java @@ -0,0 +1,654 @@ +/* + * 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.codegen.builders.TrackedValue.changedValue; +import static org.javahelpers.codegen.builders.TrackedValue.initialValue; +import static org.javahelpers.codegen.builders.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 org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.builders.BuilderToStringStyle; +import org.javahelpers.codegen.builders.IBuilderBase; +import org.javahelpers.codegen.builders.TrackedValue; +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; + +/** + * 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(annotationDtoBuilder -> annotationDtoBuilder)
+ *     .annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build())
+ *     .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(methodDtoBuilder -> methodDtoBuilder)
+ *     .methods(MethodDtoBuilder.create().build(), MethodDtoBuilder.create().build())
+ *     .add2Methods(MethodDtoBuilder.create().build())
+ *     .typeName("example typeName")
+ *     .typeName("Hello %s", "World")
+ *     .typeName(() -> "example typeName")
+ *     .typeName(sb -> sb.append("text"))
+ *     .build();
+ * }
+ */ +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; + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param annotationType the annotation type (not null) + * @return current instance of builder + */ + public NestedTypeDtoBuilder add2Annotations(Class annotationType) { + return add2Annotations(AnnotationDtoBuilder.create().annotationType(annotationType).build()); + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param packageName package of the annotation type + * @param className simple name of the annotation type + * @return current instance of builder + */ + public NestedTypeDtoBuilder add2Annotations(String packageName, String className) { + return add2Annotations( + AnnotationDtoBuilder.create().annotationType(packageName, className).build()); + } + + /** + * Adds one element to annotations, configured through its builder. + * + * @param annotationBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public NestedTypeDtoBuilder annotations( + Consumer annotationBuilderConsumer) { + AnnotationDtoBuilder elementBuilder = AnnotationDtoBuilder.create(); + annotationBuilderConsumer.accept(elementBuilder); + return add2Annotations(elementBuilder.build()); + } + + /** + * Adds elements to annotations, each configured through its builder. + * + * @param annotationBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final NestedTypeDtoBuilder annotations( + Consumer... annotationBuilderConsumers) { + for (Consumer consumer : annotationBuilderConsumers) { + annotations(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * Adds one element to methods, configured through its builder. + * + * @param methodBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public NestedTypeDtoBuilder methods(Consumer methodBuilderConsumer) { + MethodDtoBuilder elementBuilder = MethodDtoBuilder.create(); + methodBuilderConsumer.accept(elementBuilder); + return add2Methods(elementBuilder.build()); + } + + /** + * Adds elements to methods, each configured through its builder. + * + * @param methodBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final NestedTypeDtoBuilder methods(Consumer... methodBuilderConsumers) { + for (Consumer consumer : methodBuilderConsumers) { + methods(consumer); + } + 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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/test/java/org/javahelpers/codegen/model/core/CodegenDtoBuildersTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/model/core/CodegenDtoBuildersTest.java new file mode 100644 index 00000000..60735f20 --- /dev/null +++ b/codegen-core/src/test/java/org/javahelpers/codegen/model/core/CodegenDtoBuildersTest.java @@ -0,0 +1,308 @@ +/* + * 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.*; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.*; +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.*; +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(Deprecated.class) + .add2Members("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(Deprecated.class) + .add2Members("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(List.class) + .add2FieldTypeImports(List.class) + .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) + .add2Parameters(parameter) + .add2GenericParameters(generic) + .add2Annotations(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() + .add2Parameters(parameter) + .add2Annotations(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") + .add2Methods(method) + .add2Annotations(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]).add2Tags(tag).build(); + assertEquals("Summary", dto.getDescription()); + assertEquals(List.of(tag), dto.getTags()); + } + + @Test + void buildsCodeTemplate() { + assertCode( + CodeTemplateDtoBuilder.create() + .codeFormat("return $value:S;") + .add2CodeArguments(ARGUMENT) + .add2CodeBlockImports(List.class) + .build()); + } + + @Test + void buildsMethodCode() { + assertCode(code()); + } + + @Test + void buildsJavadocCodeBlock() { + assertCode( + JavadocCodeBlockDtoBuilder.create() + .codeFormat("return $value:S;") + .add2CodeArguments(ARGUMENT) + .add2CodeBlockImports(List.class) + .build()); + } + + @Test + void buildsGenerationTarget() { + InterfaceName contract = new InterfaceName("java.lang", "Runnable"); + GenerationTargetClassDto dto = + GenerationTargetClassDtoBuilder.create() + .typeName("example", "Target") + .classFields(f -> f.fieldName("value")) + .methods(m -> m.methodName("apply")) + .constructors(c -> {}) + .generics(g -> g.name("T").upperBounds(List.of(TypeName.of(Number.class)))) + .interfaces(Set.of(contract)) + .nestedTypes(n -> n.typeName("Factory")) + .add2ClassAnnotations(ANNOTATION) + .add2Imports(List.class) + .build(); + assertEquals(new TypeName("example", "Target"), dto.getTypeName()); + assertEquals("value", dto.getClassFields().get(0).getFieldName()); + assertEquals("apply", dto.getMethods().get(0).getMethodName()); + assertEquals(1, dto.getConstructors().size()); + assertEquals("T", dto.getGenerics().get(0).getName()); + assertEquals(Set.of(contract), dto.getInterfaces()); + assertEquals("Factory", dto.getNestedTypes().get(0).getTypeName()); + 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(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 00000000..99498ce4 --- /dev/null +++ b/codegen-core/src/test/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilderTest.java @@ -0,0 +1,195 @@ +/* + * 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 java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.enums.FormattingMode; +import org.javahelpers.codegen.model.annotation.InterfaceName; +import org.javahelpers.codegen.model.imports.RegularImport; +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.javahelpers.codegen.model.type.TypeNameArray; +import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNameList; +import org.javahelpers.codegen.model.type.TypeNameMap; +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("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("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("test", "EmptyBuilder").build(); + + assertNull(dto.getClassAccessModifier()); + assertNull(dto.getClassJavadoc()); + assertNull(dto.getSuperType()); + assertNull(dto.getFormattingMode()); + } + + @Test + void builderInitializedFromInstanceAppliesChanges() { + GenerationTargetClassDto original = + GenerationTargetClassDtoBuilder.create() + .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 buildsWholeDtoInOneFluentStream() { + // One continuous stream: every nested DTO is configured through the + // Consumer-based collection helpers, no intermediate variables. + GenerationTargetClassDto dto = + GenerationTargetClassDtoBuilder.create() + .typeName("example", "Target") + .superType(Number.class) + .classFields(field -> field.fieldName("value").fieldTypeList(String.class)) + .constructors( + constructor -> + constructor.parameters( + parameter -> + parameter.parameterName("arg").parameterTypeNameArray(String.class))) + .methods( + method -> + method + .methodName("apply") + .returnTypeGeneric(Optional.class, String.class) + .parameters( + parameter -> + parameter + .parameterName("v") + .parameterTypeNameMap(String.class, Integer.class)) + .genericParameters( + generic -> + generic + .name("T") + .add2UpperBounds(Number.class) + .add2UpperBoundsSet(TypeName.of(Number.class))) + .annotations(annotation -> annotation.annotationType(Deprecated.class))) + .generics(generic -> generic.name("E")) + .interfaces(new InterfaceName("java.lang", "Runnable")) + .nestedTypes( + nested -> nested.typeName("Factory").methods(method -> method.methodName("create"))) + .classAnnotations( + annotation -> + annotation + .annotationType("java.lang", "Deprecated") + .members(Map.of("since", "\"1\""))) + .imports(new RegularImport(TypeName.of(List.class))) + .build(); + + assertEquals(new TypeName("example", "Target"), dto.getTypeName()); + assertEquals(TypeName.of(Number.class), dto.getSuperType()); + assertEquals("value", dto.getClassFields().get(0).getFieldName()); + assertEquals(TypeNameList.of(String.class), dto.getClassFields().get(0).getFieldType()); + assertEquals("arg", dto.getConstructors().get(0).getParameters().get(0).getParameterName()); + assertEquals( + TypeNameArray.of(String.class), + dto.getConstructors().get(0).getParameters().get(0).getParameterType()); + assertEquals("apply", dto.getMethods().get(0).getMethodName()); + assertEquals( + TypeNameGeneric.of(Optional.class, String.class), dto.getMethods().get(0).getReturnType()); + assertEquals("v", dto.getMethods().get(0).getParameters().get(0).getParameterName()); + assertEquals( + TypeNameMap.of(String.class, Integer.class), + dto.getMethods().get(0).getParameters().get(0).getParameterType()); + assertEquals(2, dto.getMethods().get(0).getGenericParameters().get(0).getUpperBounds().size()); + assertEquals("T", dto.getMethods().get(0).getGenericParameters().get(0).getName()); + assertEquals("E", dto.getGenerics().get(0).getName()); + assertEquals(Set.of(new InterfaceName("java.lang", "Runnable")), dto.getInterfaces()); + assertEquals("Factory", dto.getNestedTypes().get(0).getTypeName()); + assertEquals("create", dto.getNestedTypes().get(0).getMethods().get(0).getMethodName()); + assertEquals( + Map.of("since", "\"1\""), dto.getClassAnnotations().iterator().next().getMembers()); + assertEquals(Set.of(new RegularImport(TypeName.of(List.class))), dto.getImports()); + + // The DTO implements its builder's With interface: copy-and-modify in one call. + GenerationTargetClassDto renamed = dto.with(b -> b.typeName(Integer.class)); + assertEquals(TypeName.of(Integer.class), renamed.getTypeName()); + assertEquals(new TypeName("example", "Target"), dto.getTypeName()); + assertEquals(TypeName.of(Number.class), dto.getSuperType()); + assertEquals(dto.getClassFields(), renamed.getClassFields()); + } + + @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 b4a7f31a..b8d5f6db 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,12 @@ 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.MethodParameterDto; +import org.javahelpers.codegen.model.method.CodeTemplateDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameGeneric; import org.javahelpers.codegen.model.type.TypeNameWildcard; @@ -49,15 +50,14 @@ class ImportCollectorTest { @Test void convenienceImportMethodsTraverseWildcardBounds() { TypeNameWildcard wildcard = TypeNameWildcard.extendsBound(TypeName.of(Instant.class)); - GenerationTargetClassDto target = classDef("test", "Target"); - ClassFieldDto field = new ClassFieldDto(); - CodeTemplateDto code = new CodeTemplateDto(); - target.addImport(new TypeNameWildcard()); - target.addImport(wildcard); - field.addImport(new TypeNameWildcard()); - field.addImport(wildcard); - code.addCodeBlockImport(new TypeNameWildcard()); - code.addCodeBlockImport(wildcard); + GenerationTargetClassDto target = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "Target") + .add2Imports(Instant.class) + .build(); + ClassFieldDto field = ClassFieldDtoBuilder.create().add2FieldTypeImports(Instant.class).build(); + CodeTemplateDto code = + CodeTemplateDtoBuilder.create().add2CodeBlockImports(Instant.class).build(); String expected = """ java.time.Instant"""; @@ -93,35 +93,30 @@ private static List fqns(GenerationTargetClassDto classDef) { .toList(); } - private static GenerationTargetClassDto classDef(String pkg, String name) { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName(pkg, name)); - return classDef; - } - - 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; - } - @Test void skipsJavaLangAndSamePackageTypes() { - GenerationTargetClassDto classDef = classDef("com.example", "Dto"); - classDef.addClassField(field("samePackage", "com.example", "Sibling")); - classDef.addClassField(field("langType", "java.lang", "String")); - classDef.addClassField(field("needed", "java.util", "Optional")); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("com.example", "Dto") + .classFields( + f -> f.fieldName("samePackage").fieldType("com.example", "Sibling"), + f -> f.fieldName("langType").fieldType("java.lang", "String"), + f -> f.fieldName("needed").fieldType("java.util", "Optional")) + .build(); assertEquals(List.of("java.util.Optional"), fqns(classDef)); } @Test void importsSortedAlphabetically() { - GenerationTargetClassDto classDef = classDef("com.example", "Dto"); - classDef.addClassField(field("z", "java.util", "TreeSet")); - classDef.addClassField(field("a", "java.util", "ArrayDeque")); - classDef.addClassField(field("m", "java.time", "Instant")); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("com.example", "Dto") + .classFields( + f -> f.fieldName("z").fieldType("java.util", "TreeSet"), + f -> f.fieldName("a").fieldType("java.util", "ArrayDeque"), + f -> f.fieldName("m").fieldType("java.time", "Instant")) + .build(); assertEquals( List.of("java.time.Instant", "java.util.ArrayDeque", "java.util.TreeSet"), fqns(classDef)); @@ -129,24 +124,29 @@ void importsSortedAlphabetically() { @Test void toleratesNullImportStatements() { - GenerationTargetClassDto classDef = classDef("com.example", "Dto"); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("com.example", "Dto") + .classFields(f -> f.fieldName("needed").fieldType("java.util", "Optional")) + .build(); classDef.addImport((ImportStatement) null); - classDef.addClassField(field("needed", "java.util", "Optional")); assertEquals(List.of("java.util.Optional"), fqns(classDef)); } @Test 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")); - method.addParameter(param); - classDef.addMethod(method); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("com.example", "Dto") + .classFields(f -> f.fieldName("mapping").fieldType("com.example", "StringIntegerMap")) + .methods( + m -> + m.methodName("values") + .returnType("java.util", "Collection") + .parameters( + p -> p.parameterName("key").parameterTypeName("com.other", "KeyDto"))) + .build(); assertTrue(fqns(classDef).contains("java.util.Collection")); assertTrue(fqns(classDef).contains("com.other.KeyDto")); diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java index 10d42bb7..d3e09b17 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 @@ -27,17 +27,18 @@ import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.util.List; import org.javahelpers.codegen.CodeGenerationException; import org.javahelpers.codegen.SourceFormatter; import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.enums.FormattingMode; import org.javahelpers.codegen.logging.ProcessingLogger; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; -import org.javahelpers.codegen.model.method.ConstructorDto; -import org.javahelpers.codegen.model.method.MethodCodeDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; +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.MethodParameterDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.roaster.exceptions.RoasterMapperException; import org.javahelpers.codegen.testing.CapturingProcessingLogger; @@ -64,18 +65,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); - - MethodCodeDto code = new MethodCodeDto(); - code.setCodeFormat("return $value:X;"); - code.addCodeArgument(new UnsupportedPlaceholder("value", "irrelevant")); - - ConstructorDto constructor = new ConstructorDto(); - constructor.setVisibility(AccessModifier.PUBLIC); - constructor.setMethodCodeDto(code); - classDef.addConstructor(constructor); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("com.example", "FailingBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .constructors( + c -> + c.visibility(AccessModifier.PUBLIC) + .methodCodeDto( + MethodCodeDtoBuilder.create() + .codeFormat("return $value:X;") + .add2CodeArguments( + new UnsupportedPlaceholder("value", "irrelevant")) + .build())) + .build(); ProcessingLogger logger = CapturingProcessingLogger.create().logger(); RoasterCodeGenerator generator = @@ -97,12 +100,13 @@ void shouldWrapRenderingRuntimeExceptionInCodeGenerationException() { */ @Test void shouldKeepFirstMethodAndWarnOnDuplicateSignature() { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("com.example", "DuplicateSignatureBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - classDef.addMethod(duplicateSignatureMethod("first")); - classDef.addMethod(duplicateSignatureMethod("second")); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("com.example", "DuplicateSignatureBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .methods(List.of(duplicateSignatureMethod("first"), duplicateSignatureMethod("second"))) + .build(); CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); RoasterCodeGenerator generator = @@ -117,14 +121,12 @@ 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)); - method.addParameter(parameter); - method.setCode("return this; // " + marker); - return method; + return MethodDtoBuilder.create() + .methodName("name") + .returnType(new TypeName("com.example", "DuplicateSignatureBuilder")) + .modifier(AccessModifier.PUBLIC) + .code("return this; // " + marker) + .parameters(p -> p.parameterName("value").parameterTypeName(String.class)) + .build(); } } 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 f6777256..4b277572 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 @@ -30,21 +30,18 @@ import com.google.testing.compile.Compilation; import com.google.testing.compile.JavaFileObjects; import java.util.List; +import java.util.Map; 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.GenerationTargetClassDto; -import org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDto; -import org.javahelpers.codegen.model.javadoc.JavadocDto; -import org.javahelpers.codegen.model.method.ConstructorDto; -import org.javahelpers.codegen.model.method.MethodDto; -import org.javahelpers.codegen.model.method.MethodParameterDto; -import org.javahelpers.codegen.model.type.GenericParameterDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocTagDto; import org.javahelpers.codegen.model.type.NestedTypeDto; 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; @@ -61,12 +58,14 @@ class RoasterCodeGeneratorTest { @Test void preservesLeadingFieldTypeAnnotation() throws Exception { - GenerationTargetClassDto classDef = annotatedClassDefinition(); - ClassFieldDto field = new ClassFieldDto(); - field.setFieldName("value"); - field.setFieldType(stringTypeNullableAnnotated()); - field.setVisibility(AccessModifier.PRIVATE); - classDef.addClassField(field); + GenerationTargetClassDto classDef = + annotatedClassDefinition() + .classFields( + f -> + f.fieldName("value") + .fieldType(stringTypeNullableAnnotated()) + .visibility(AccessModifier.PRIVATE)) + .build(); assertAnnotatedSource( """ @@ -82,14 +81,16 @@ public class AnnotatedTypes { @Test void preservesLeadingReturnTypeAnnotation() throws Exception { - GenerationTargetClassDto classDef = annotatedClassDefinition(); - MethodDto method = new MethodDto("value", stringTypeNullableAnnotated()); - method.setModifier(AccessModifier.PUBLIC); - method.setCode("return null;"); - AnnotationDto deprecated = new AnnotationDto(); - deprecated.setAnnotationType(TypeName.of(Deprecated.class)); - method.addAnnotation(deprecated); - classDef.addMethod(method); + GenerationTargetClassDto classDef = + annotatedClassDefinition() + .methods( + m -> + m.methodName("value") + .returnType(stringTypeNullableAnnotated()) + .modifier(AccessModifier.PUBLIC) + .code("return null;") + .annotations(a -> a.annotationType(Deprecated.class))) + .build(); assertAnnotatedSource( """ @@ -108,24 +109,29 @@ public String value() { @Test void preservesAnnotatedGenericReturnType() throws Exception { - GenerationTargetClassDto classDef = annotatedClassDefinition(); TypeName listOfStringsAnnotated = new TypeNameGeneric(TypeName.of(List.class), stringTypeNullableAnnotated()); - MethodDto method = new MethodDto("values", listOfStringsAnnotated); - method.setModifier(AccessModifier.PUBLIC); - method.setCode("return null;"); - classDef.addMethod(method); - - NestedTypeDto nested = new NestedTypeDto(); - nested.setTypeName("Nested"); - nested.setKind(NestedTypeDto.NestedTypeKind.INTERFACE); - nested.setVisibility(AccessModifier.PUBLIC); TypeName listOfListsAnnotated = new TypeNameGeneric(TypeName.of(List.class), listOfStringsAnnotated); - MethodDto nestedMethod = new MethodDto("values", listOfListsAnnotated); - nestedMethod.setCode("return null;"); - nested.addMethod(nestedMethod); - classDef.addNestedType(nested); + GenerationTargetClassDto classDef = + annotatedClassDefinition() + .methods( + m -> + m.methodName("values") + .returnType(listOfStringsAnnotated) + .modifier(AccessModifier.PUBLIC) + .code("return null;")) + .nestedTypes( + n -> + n.typeName("Nested") + .kind(NestedTypeDto.NestedTypeKind.INTERFACE) + .visibility(AccessModifier.PUBLIC) + .methods( + m -> + m.methodName("values") + .returnType(listOfListsAnnotated) + .code("return null;"))) + .build(); assertAnnotatedSource( """ @@ -169,30 +175,27 @@ 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("com.example", "EmptyBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); assertEquals("mem:///com/example/EmptyBuilder.java", generate(empty).writtenUri().toString()); } @Test void qualifiesCollidingDateTypeNames() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "DateBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - - ClassFieldDto utilDate = new ClassFieldDto(); - utilDate.setFieldName("utilDate"); - utilDate.setFieldType(new TypeName("java.util", "Date")); - classDef.addClassField(utilDate); - - ClassFieldDto sqlDate = new ClassFieldDto(); - sqlDate.setFieldName("sqlDate"); - sqlDate.setFieldType(new TypeName("java.sql", "Date")); - classDef.addClassField(sqlDate); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "DateBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .classFields( + f -> f.fieldName("utilDate").fieldType("java.util", "Date"), + f -> f.fieldName("sqlDate").fieldType("java.sql", "Date")) + .build(); assertGeneratedSource( """ @@ -207,20 +210,17 @@ public class DateBuilder { @Test void qualifiesCollidingGenericListTypeNames() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "ListBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - - ClassFieldDto utilList = new ClassFieldDto(); - utilList.setFieldName("utilList"); - utilList.setFieldType(new TypeNameGeneric(java.util.List.class, String.class)); - classDef.addClassField(utilList); - - ClassFieldDto awtList = new ClassFieldDto(); - awtList.setFieldName("awtList"); - awtList.setFieldType(new TypeName("java.awt", "List")); - classDef.addClassField(awtList); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "ListBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .classFields( + f -> + f.fieldName("utilList") + .fieldType(new TypeNameGeneric(java.util.List.class, String.class)), + f -> f.fieldName("awtList").fieldType("java.awt", "List")) + .build(); assertGeneratedSource( """ @@ -235,35 +235,30 @@ public class ListBuilder { @Test void qualifiesCollidingAnnotationAndInterfaceSimpleNames() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "AmbiguousBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - - // Two distinct NonNull annotations on different declaration sites: the one that wins the - // import renders simple, the other stays qualified. - AnnotationDto classAnnotation = new AnnotationDto(); - classAnnotation.setAnnotationType(new TypeName("org.a", "NonNull")); - classDef.addClassAnnotation(classAnnotation); - - MethodDto method = new MethodDto("x", TypeName.of(String.class)); - method.setModifier(AccessModifier.PUBLIC); - method.setCode("return null;"); - AnnotationDto methodAnnotation = new AnnotationDto(); - methodAnnotation.setAnnotationType(new TypeName("org.b", "NonNull")); - method.addAnnotation(methodAnnotation); - MethodParameterDto param = new MethodParameterDto(); - param.setParameterName("in"); - param.setParameterTypeName(TypeName.of(String.class)); - AnnotationDto paramAnnotation = new AnnotationDto(); - paramAnnotation.setAnnotationType(new TypeName("org.a", "NonNull")); - param.addAnnotation(paramAnnotation); - method.addParameter(param); - classDef.addMethod(method); - - // Two distinct interfaces sharing a simple name. - classDef.addInterface(new InterfaceName("org.a", "Cloneable")); - classDef.addInterface(new InterfaceName("org.b", "Cloneable")); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "AmbiguousBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + // Two distinct NonNull annotations on different declaration sites: the one that wins + // the import renders simple, the other stays qualified. + .classAnnotations(a -> a.annotationType("org.a", "NonNull")) + .methods( + m -> + m.methodName("x") + .returnType(String.class) + .modifier(AccessModifier.PUBLIC) + .code("return null;") + .annotations(a -> a.annotationType("org.b", "NonNull")) + .parameters( + p -> + p.parameterName("in") + .parameterTypeName(String.class) + .annotations(a -> a.annotationType("org.a", "NonNull")))) + // Two distinct interfaces sharing a simple name. + .interfaces( + new InterfaceName("org.a", "Cloneable"), new InterfaceName("org.b", "Cloneable")) + .build(); assertGeneratedSource( """ @@ -282,29 +277,25 @@ public String x(@NonNull String in) { @Test void qualifiesCollidingTypeUseAnnotationSimpleNames() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "AmbiguousBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - // A field type carrying a type-use annotation whose simple name collides with a method // annotation type: both usages must render qualified. - AnnotationDto methodAnnotation = new AnnotationDto(); - methodAnnotation.setAnnotationType(new TypeName("org.a", "Nullable")); - MethodDto method = new MethodDto("x", TypeName.of(String.class)); - method.setModifier(AccessModifier.PUBLIC); - method.setCode("return null;"); - method.addAnnotation(methodAnnotation); - classDef.addMethod(method); - - AnnotationDto typeUseAnnotation = new AnnotationDto(); - typeUseAnnotation.setAnnotationType(new TypeName("org.b", "Nullable")); TypeName fieldType = TypeName.of(String.class); - fieldType.addAnnotation(typeUseAnnotation); - ClassFieldDto field = new ClassFieldDto(); - field.setFieldName("value"); - field.setFieldType(fieldType); - classDef.addClassField(field); + fieldType.addAnnotation( + AnnotationDtoBuilder.create().annotationType("org.b", "Nullable").build()); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "AmbiguousBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .methods( + m -> + m.methodName("x") + .returnType(String.class) + .modifier(AccessModifier.PUBLIC) + .code("return null;") + .annotations(a -> a.annotationType("org.a", "Nullable"))) + .classFields(f -> f.fieldName("value").fieldType(fieldType)) + .build(); assertGeneratedSource( """ @@ -323,18 +314,20 @@ 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")); - generated.addMember("value", "\"simple-builders\""); - classDef.addClassAnnotation(generated); - classDef.setSuperType(new TypeName("test", "AbstractBuilder")); - InterfaceName iface = new InterfaceName("java.io", "Serializable"); - classDef.addInterface(iface); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "AnnotatedBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .classJavadoc( + JavadocDtoBuilder.create().format("Builder for {@link Person}.").args().build()) + .superType(new TypeName("test", "AbstractBuilder")) + .classAnnotations( + a -> + a.annotationType("javax.annotation", "Generated") + .members(Map.of("value", "\"simple-builders\""))) + .interfaces(interfaces -> interfaces.add(new InterfaceName("java.io", "Serializable"))) + .build(); assertGeneratedSource( """ @@ -352,28 +345,25 @@ 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)); - 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"); - methodGeneric.addUpperBound(TypeName.of(Number.class)); - genericMethod.addGenericParameter(methodGeneric); - MethodParameterDto param = new MethodParameterDto(); - param.setParameterName("input"); - param.setParameterTypeName(new TypeNameVariable("R")); - genericMethod.addParameter(param); - genericMethod.setCode("return null;"); - classDef.addMethod(genericMethod); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "GenericBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .generics(g -> g.name("T").add2UpperBounds(Number.class)) + .methods( + m -> + m.methodName("of") + .returnType(new TypeNameVariable("T")) + .modifier(AccessModifier.PUBLIC) + .isStatic(true) + .code("return null;") + .genericParameters(g -> g.name("R").add2UpperBounds(Number.class)) + .parameters( + p -> + p.parameterName("input") + .parameterTypeName(new TypeNameVariable("R")))) + .build(); assertGeneratedSource( """ @@ -388,22 +378,22 @@ public static T of(R input) { @Test void generatesVoidVarargsAndPackagePrivateMembers() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "MiscBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - - MethodDto voidMethod = new MethodDto("close", null); - voidMethod.setModifier(AccessModifier.PACKAGE_PRIVATE); - MethodParameterDto varArgs = new MethodParameterDto(); - varArgs.setParameterName("items"); - varArgs.setParameterTypeName(new TypeNameArray(TypeName.of(String.class))); - voidMethod.addParameter(varArgs); - AnnotationDto suppressWarnings = new AnnotationDto(); - suppressWarnings.setAnnotationType(TypeName.of(SuppressWarnings.class)); - suppressWarnings.addMember("value", "\"unchecked\""); - voidMethod.addAnnotation(suppressWarnings); - classDef.addMethod(voidMethod); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "MiscBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .methods( + m -> + m.methodName("close") + .modifier(AccessModifier.PACKAGE_PRIVATE) + .parameters( + p -> p.parameterName("items").parameterTypeNameArray(String.class)) + .annotations( + a -> + a.annotationType(SuppressWarnings.class) + .members(Map.of("value", "\"unchecked\"")))) + .build(); assertGeneratedSource( """ @@ -418,20 +408,27 @@ void close(String... items) { @Test void generatesJavadocCodeBlockAndValuelessTag() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "DocBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - - MethodDto method = new MethodDto("apply", TypeNamePrimitive.VOID); - method.setModifier(AccessModifier.PUBLIC); - JavadocDto javadoc = new JavadocDto("Applies the values."); - javadoc.addTag("since"); - JavadocCodeBlockDto codeBlock = new JavadocCodeBlockDto(); - codeBlock.setCodeFormat("builder.apply();"); - javadoc.setExampleUsageCodeBlock(codeBlock); - method.setJavadoc(javadoc); - classDef.addMethod(method); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "DocBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .methods( + m -> + m.methodName("apply") + .returnType(TypeNamePrimitive.VOID) + .modifier(AccessModifier.PUBLIC) + .javadoc( + javadoc -> + javadoc + .format("Applies the values.") + .args() + .add2Tags(JavadocTagDto.withoutValue("since")) + .exampleUsageCodeBlock( + JavadocCodeBlockDtoBuilder.create() + .codeFormat("builder.apply();") + .build()))) + .build(); assertGeneratedSource( """ @@ -452,17 +449,17 @@ public void apply() { @Test void generatesNestedInterfaceWithAbstractMethod() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "NestedBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - - NestedTypeDto nested = new NestedTypeDto(); - nested.setTypeName("Callback"); - nested.setKind(NestedTypeDto.NestedTypeKind.INTERFACE); - MethodDto abstractMethod = new MethodDto("onDone", TypeNamePrimitive.VOID); - nested.addMethod(abstractMethod); - classDef.addNestedType(nested); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "NestedBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .nestedTypes( + n -> + n.typeName("Callback") + .kind(NestedTypeDto.NestedTypeKind.INTERFACE) + .methods(m -> m.methodName("onDone").returnType(TypeNamePrimitive.VOID))) + .build(); assertGeneratedSource( """ @@ -478,28 +475,26 @@ 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"); - 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")); - param.addAnnotation(paramAnnotation); - ctor.addParameter(param); - classDef.addConstructor(ctor); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "CtorBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .classFields( + f -> + f.fieldName("DEFAULT_SIZE") + .fieldType(TypeNamePrimitive.INT) + .visibility(AccessModifier.PRIVATE) + .literalInitializer("42")) + .constructors( + c -> + c.visibility(AccessModifier.PROTECTED) + .parameters( + p -> + p.parameterName("capacity") + .parameterTypeName(TypeNamePrimitive.INT) + .annotations(a -> a.annotationType("test.anno", "NonNull")))) + .build(); assertGeneratedSource( """ @@ -515,21 +510,24 @@ 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"); - nested.addMethod(nestedMethod); - classDef.addNestedType(nested); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "OuterBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .nestedTypes( + n -> + n.typeName("Helper") + .kind(NestedTypeDto.NestedTypeKind.CLASS) + .visibility(AccessModifier.PUBLIC) + .javadoc(javadoc -> javadoc.format("Nested helper.").args()) + .methods( + m -> + m.methodName("assist") + .returnType(TypeNamePrimitive.VOID) + .modifier(AccessModifier.PRIVATE) + .code("// nothing"))) + .build(); assertGeneratedSource( """ @@ -548,26 +546,30 @@ 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."); - javadoc.addParam("values", "items to add"); - javadoc.addReturn("this builder"); - method.setJavadoc(javadoc); - AnnotationDto override_ = new AnnotationDto(); - override_.setAnnotationType(TypeName.of(Override.class)); - method.addAnnotation(override_); - MethodParameterDto param = new MethodParameterDto(); - param.setParameterName("values"); - param.setParameterTypeName(new TypeNameGeneric(List.class, String.class)); - method.addParameter(param); - method.setCode("return null;"); - classDef.addMethod(method); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName("test", "RichBuilder") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .methods( + m -> + m.methodName("items") + .returnTypeGeneric(List.class, String.class) + .modifier(AccessModifier.PUBLIC) + .javadoc( + javadoc -> + javadoc + .format("Adds items.") + .args() + .add2Tags(new JavadocTagDto("param", "values items to add")) + .add2Tags(new JavadocTagDto("return", "this builder"))) + .code("return null;") + .annotations(a -> a.annotationType(Override.class)) + .parameters( + p -> + p.parameterName("values") + .parameterTypeNameGeneric(List.class, String.class))) + .build(); assertGeneratedSource( """ @@ -612,50 +614,45 @@ 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()"); - 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)); - 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;"); - target.addMethod(build); - return target; + return GenerationTargetClassDtoBuilder.create() + .typeName(builderType) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .classFields( + f -> + f.fieldName("target") + .fieldType(personType) + .visibility(AccessModifier.PRIVATE) + .literalInitializer("new Person()")) + .methods( + m -> + m.methodName("name") + .returnType(builderType) + .modifier(AccessModifier.PUBLIC) + .code( + """ + target.setName(name); + return this;""") + .parameters(p -> p.parameterName("name").parameterTypeName(String.class)), + m -> + m.methodName("build") + .returnType(personType) + .modifier(AccessModifier.PUBLIC) + .code("return target;")) + .build(); } - private static GenerationTargetClassDto annotatedClassDefinition() { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "AnnotatedTypes")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - return classDef; + private static GenerationTargetClassDtoBuilder annotatedClassDefinition() { + return GenerationTargetClassDtoBuilder.create() + .typeName("test", "AnnotatedTypes") + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE); } private static TypeName stringTypeNullableAnnotated() { - AnnotationDto nullable = new AnnotationDto(); - nullable.setAnnotationType(new TypeName("test.anno", "Nullable")); TypeName type = TypeName.of(String.class); - type.addAnnotation(nullable); + type.addAnnotation( + AnnotationDtoBuilder.create().annotationType("test.anno", "Nullable").build()); return type; } 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 1684f035..552ddce4 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/pom.xml b/pom.xml index 8ee07c5b..18709f72 100644 --- a/pom.xml +++ b/pom.xml @@ -84,6 +84,7 @@ Only genuine boilerplate is excluded (DTO model, exception classes, constants holders, generated sources); mapper logic is intentionally measured. --> **/processor/model/**,**/codegen/model/**,**/exceptions/**,**/generated/**,**/JavadocConstants.java + **/codegen/model/**,**/processor/model/**,**/codegen/builders/** 3.16.0 diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/BuilderImplementationAnnotationEnhancer.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/BuilderImplementationAnnotationEnhancer.java index dfc01d41..59b219eb 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/BuilderImplementationAnnotationEnhancer.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/BuilderImplementationAnnotationEnhancer.java @@ -25,6 +25,7 @@ import org.javahelpers.codegen.analysis.JavaLangMapper; 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.processor.generators.BuilderEnhancer; @@ -96,13 +97,11 @@ public void enhanceBuilder(BuilderDefinitionDto builderDto, BuilderProcessingCon * @return the annotation DTO for @BuilderImplementation */ private AnnotationDto createBuilderImplementationAnnotation(BuilderDefinitionDto builderDto) { - AnnotationDto annotation = new AnnotationDto(); - annotation.setAnnotationType(JavaLangMapper.map2TypeName(BuilderImplementation.class)); - - // Add forClass member with the target DTO class - annotation.addMember( - "forClass", builderDto.getBuildingTargetTypeName().getClassName() + ".class"); - - return annotation; + return AnnotationDtoBuilder.create() + .annotationType(JavaLangMapper.map2TypeName(BuilderImplementation.class)) + .members( + m -> + m.put("forClass", builderDto.getBuildingTargetTypeName().getClassName() + ".class")) + .build(); } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ClassJavaDocEnhancer.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ClassJavaDocEnhancer.java index e8386af6..43a7f98f 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ClassJavaDocEnhancer.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ClassJavaDocEnhancer.java @@ -26,6 +26,7 @@ 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.type.TypeName; import org.javahelpers.simple.builders.processor.generators.BuilderEnhancer; import org.javahelpers.simple.builders.processor.model.core.BuilderDefinitionDto; @@ -130,15 +131,17 @@ public void enhanceBuilder(BuilderDefinitionDto builderDto, BuilderProcessingCon */ private JavadocDto createClassJavadoc(TypeName targetType) { String qualifiedClassName = targetType.getFullQualifiedName(); - return new JavadocDto( - """ - Builder for {@code %s}. -

- This builder provides a fluent API for creating instances of %s 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.\ - """, - qualifiedClassName, qualifiedClassName); + return JavadocDtoBuilder.create() + .format( + """ + Builder for {@code %s}. +

+ This builder provides a fluent API for creating instances of %s 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.\ + """, + qualifiedClassName, qualifiedClassName) + .build(); } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ConditionalEnhancer.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ConditionalEnhancer.java index c4fe3dea..09d61f9c 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ConditionalEnhancer.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ConditionalEnhancer.java @@ -26,13 +26,15 @@ import java.util.function.BooleanSupplier; import org.javahelpers.codegen.analysis.JavaLangMapper; import org.javahelpers.codegen.enums.AccessModifier; -import org.javahelpers.codegen.model.javadoc.JavadocDto; -import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocTagDto; +import org.javahelpers.codegen.model.method.MethodParameterDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.simple.builders.processor.generators.BuilderEnhancer; import org.javahelpers.simple.builders.processor.generators.util.MethodGeneratorUtil; import org.javahelpers.simple.builders.processor.model.core.BuilderDefinitionDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; /** @@ -116,10 +118,14 @@ public void enhanceBuilder(BuilderDefinitionDto builderDto, BuilderProcessingCon /** Creates the conditional(BooleanSupplier, Consumer, Consumer) method. */ private BuilderMethodDto createConditionalMethod(BuilderDefinitionDto builderDto) { - BuilderMethodDto method = new BuilderMethodDto("conditional", builderDto.getBuilderTypeName()); - method.setOrdering(ORDERING_CONDITIONAL); - method.setPriority(BuilderMethodDto.PRIORITY_HIGHEST); - method.setModifier(AccessModifier.PUBLIC); + BuilderMethodDto method = + BuilderMethodDtoBuilder.create() + .methodName("conditional") + .returnType(builderDto.getBuilderTypeName()) + .ordering(ORDERING_CONDITIONAL) + .priority(BuilderMethodDto.PRIORITY_HIGHEST) + .modifier(AccessModifier.PUBLIC) + .build(); // Add parameters addConditionalPositiveNegativeParameters(method, builderDto.getBuilderTypeName()); @@ -136,22 +142,30 @@ private BuilderMethodDto createConditionalMethod(BuilderDefinitionDto builderDto """); method.setJavadoc( - new JavadocDto( - "Conditionally applies builder modifications based on a condition evaluation.") - .addParam("condition", "the condition to evaluate") - .addParam("trueCase", "the consumer to apply if condition is true") - .addParam("falseCase", "the consumer to apply if condition is false (can be null)") - .addReturn("this builder instance")); + JavadocDtoBuilder.create() + .format("Conditionally applies builder modifications based on a condition evaluation.") + .add2Tags(new JavadocTagDto("param", "condition the condition to evaluate")) + .add2Tags( + new JavadocTagDto("param", "trueCase the consumer to apply if condition is true")) + .add2Tags( + new JavadocTagDto( + "param", "falseCase the consumer to apply if condition is false (can be null)")) + .add2Tags(new JavadocTagDto("return", "this builder instance")) + .build()); return method; } /** Creates the conditional(BooleanSupplier, Consumer) method. */ private BuilderMethodDto createConditionalPositiveOnlyMethod(BuilderDefinitionDto builderDto) { - BuilderMethodDto method = new BuilderMethodDto("conditional", builderDto.getBuilderTypeName()); - method.setOrdering(ORDERING_CONDITIONAL_POSITIVE_ONLY); - method.setPriority(BuilderMethodDto.PRIORITY_HIGHEST); - method.setModifier(AccessModifier.PUBLIC); + BuilderMethodDto method = + BuilderMethodDtoBuilder.create() + .methodName("conditional") + .returnType(builderDto.getBuilderTypeName()) + .ordering(ORDERING_CONDITIONAL_POSITIVE_ONLY) + .priority(BuilderMethodDto.PRIORITY_HIGHEST) + .modifier(AccessModifier.PUBLIC) + .build(); // Add parameters addConditionalPositiveOnlyParameters(method, builderDto.getBuilderTypeName()); @@ -160,10 +174,14 @@ private BuilderMethodDto createConditionalPositiveOnlyMethod(BuilderDefinitionDt method.setCode("return conditional(condition, yesCondition, null);"); method.setJavadoc( - new JavadocDto("Conditionally applies builder modifications if the condition is true.") - .addParam("condition", "the condition to evaluate") - .addParam("yesCondition", "the consumer to apply if condition is true") - .addReturn("this builder instance")); + JavadocDtoBuilder.create() + .format("Conditionally applies builder modifications if the condition is true.") + .add2Tags(new JavadocTagDto("param", "condition the condition to evaluate")) + .add2Tags( + new JavadocTagDto( + "param", "yesCondition the consumer to apply if condition is true")) + .add2Tags(new JavadocTagDto("return", "this builder instance")) + .build()); return method; } @@ -189,9 +207,7 @@ private void addConditionalPositiveOnlyParameters(BuilderMethodDto method, TypeN /** Adds a parameter to the method. */ private void addParameter(BuilderMethodDto method, String name, TypeName type) { - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName(name); - parameter.setParameterTypeName(type); - method.addParameter(parameter); + method.addParameter( + MethodParameterDtoBuilder.create().parameterName(name).parameterTypeName(type).build()); } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ConstructorEnhancer.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ConstructorEnhancer.java index ecd490cf..a535def5 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ConstructorEnhancer.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/ConstructorEnhancer.java @@ -24,10 +24,11 @@ package org.javahelpers.simple.builders.processor.generators.builder; -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.ConstructorDto; +import org.javahelpers.codegen.model.method.ConstructorDtoBuilder; import org.javahelpers.codegen.model.method.MethodCodeDto; -import org.javahelpers.codegen.model.method.MethodParameterDto; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNamePrimitive; import org.javahelpers.simple.builders.processor.generators.BuilderEnhancer; @@ -71,26 +72,23 @@ public void enhanceBuilder(BuilderDefinitionDto builderDto, BuilderProcessingCon /** Creates the empty constructor. */ protected ConstructorDto createEmptyConstructor(BuilderDefinitionDto builderDto) { - ConstructorDto constructor = new ConstructorDto(); - constructor.setVisibility(builderDto.getConfiguration().getBuilderConstructorAccess()); - String targetFullName = builderDto.getBuildingTargetTypeName().getFullQualifiedName(); - constructor.setJavadoc( - new JavadocDto("Empty constructor of builder for {@code %s}.", targetFullName)); - - return constructor; + return ConstructorDtoBuilder.create() + .visibility(builderDto.getConfiguration().getBuilderConstructorAccess()) + .javadoc(j -> j.format("Empty constructor of builder for {@code %s}.", targetFullName)) + .build(); } /** Creates the from-instance constructor. */ protected ConstructorDto createFromInstanceConstructor(BuilderDefinitionDto builderDto) { - ConstructorDto constructor = new ConstructorDto(); - constructor.setVisibility(builderDto.getConfiguration().getBuilderConstructorAccess()); - - // Add parameter for the DTO instance - MethodParameterDto instanceParam = new MethodParameterDto(); - instanceParam.setParameterName("instance"); - instanceParam.setParameterTypeName(builderDto.getBuildingTargetTypeName()); - constructor.addParameter(instanceParam); + ConstructorDto constructor = + ConstructorDtoBuilder.create() + .visibility(builderDto.getConfiguration().getBuilderConstructorAccess()) + .parameters( + el -> + el.parameterName("instance") + .parameterTypeName(builderDto.getBuildingTargetTypeName())) + .build(); // Build constructor code body MethodCodeDto codeDto = new MethodCodeDto(); @@ -130,8 +128,10 @@ protected ConstructorDto createFromInstanceConstructor(BuilderDefinitionDto buil String targetFullName = builderDto.getBuildingTargetTypeName().getFullQualifiedName(); constructor.setJavadoc( - new JavadocDto("Initialisation of builder for {@code %s} by a instance.", targetFullName) - .addParam("instance", "object instance for initialisiation")); + JavadocDtoBuilder.create() + .format("Initialisation of builder for {@code %s} by a instance.", targetFullName) + .add2Tags(new JavadocTagDto("param", "instance object instance for initialisiation")) + .build()); return constructor; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/CoreMethodsEnhancer.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/CoreMethodsEnhancer.java index 4b3ffe94..41efb3f5 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/CoreMethodsEnhancer.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/CoreMethodsEnhancer.java @@ -27,16 +27,16 @@ import java.util.List; import org.javahelpers.codegen.analysis.JavaLangMapper; import org.javahelpers.codegen.enums.AccessModifier; -import org.javahelpers.codegen.model.annotation.AnnotationDto; -import org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDto; -import org.javahelpers.codegen.model.javadoc.JavadocDto; -import org.javahelpers.codegen.model.type.GenericParameterDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocTagDto; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.simple.builders.processor.generators.BuilderEnhancer; import org.javahelpers.simple.builders.processor.generators.util.MethodGeneratorUtil; import org.javahelpers.simple.builders.processor.model.core.BuilderDefinitionDto; import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; /** @@ -118,16 +118,21 @@ protected BuilderMethodDto createBuildMethod(BuilderDefinitionDto builderDto) { TypeName returnType = MethodGeneratorUtil.createGenericTypeName( builderDto.getBuildingTargetTypeName(), builderDto.getGenerics()); - BuilderMethodDto method = new BuilderMethodDto("build", returnType); - method.setOrdering(ORDERING_BUILD); - method.setPriority(BuilderMethodDto.PRIORITY_HIGHEST); - method.setModifier(AccessModifier.PUBLIC); + BuilderMethodDto method = + BuilderMethodDtoBuilder.create() + .methodName("build") + .returnType(returnType) + .ordering(ORDERING_BUILD) + .priority(BuilderMethodDto.PRIORITY_HIGHEST) + .modifier(AccessModifier.PUBLIC) + .build(); // Add @Override annotation only if implementing IBuilderBase interface if (builderDto.getConfiguration().shouldImplementBuilderBase()) { - AnnotationDto overrideAnnotation = new AnnotationDto(); - overrideAnnotation.setAnnotationType(JavaLangMapper.map2TypeName(Override.class)); - method.addAnnotation(overrideAnnotation); + method.addAnnotation( + AnnotationDtoBuilder.create() + .annotationType(JavaLangMapper.map2TypeName(Override.class)) + .build()); } // Create method implementation with validation and setter application @@ -202,15 +207,15 @@ protected BuilderMethodDto createBuildMethod(BuilderDefinitionDto builderDto) { method.addArgument("dtoBaseType", builderDto.getBuildingTargetTypeName()); method.addArgument("buildResultType", returnType); method.getMethodCodeDto().addCodeBlockImport(IllegalStateException.class); - JavadocDto javadoc = new JavadocDto("Builds the configured DTO instance."); // Add example to build() method - JavadocCodeBlockDto exampleBlock = new JavadocCodeBlockDto(); String targetSimpleName = builderDto.getBuildingTargetTypeName().getClassName(); - exampleBlock.setCodeFormat("%s result = builder.build();".formatted(targetSimpleName)); - javadoc.setExampleUsageCodeBlock(exampleBlock); - - method.setJavadoc(javadoc); + method.setJavadoc( + JavadocDtoBuilder.create() + .format("Builds the configured DTO instance.") + .exampleUsageCodeBlock( + e -> e.codeFormat("%s result = builder.build();".formatted(targetSimpleName))) + .build()); return method; } @@ -220,11 +225,15 @@ protected BuilderMethodDto createStaticCreateMethod(BuilderDefinitionDto builder TypeName returnType = MethodGeneratorUtil.createGenericTypeName( builderDto.getBuilderTypeName(), builderDto.getGenerics()); - BuilderMethodDto method = new BuilderMethodDto("create", returnType); - method.setOrdering(ORDERING_CREATE); - method.setPriority(BuilderMethodDto.PRIORITY_HIGHEST); - method.setModifier(AccessModifier.PUBLIC); - method.setStatic(true); + BuilderMethodDto method = + BuilderMethodDtoBuilder.create() + .methodName("create") + .returnType(returnType) + .ordering(ORDERING_CREATE) + .priority(BuilderMethodDto.PRIORITY_HIGHEST) + .modifier(AccessModifier.PUBLIC) + .isStatic(true) + .build(); // Use appropriate code template based on whether we have generics if (builderDto.getGenerics().isEmpty()) { @@ -235,38 +244,39 @@ protected BuilderMethodDto createStaticCreateMethod(BuilderDefinitionDto builder // Add generic type parameters to method if builder has generics // (because this is a static function, the generic names from class are not available) - for (GenericParameterDto genericParam : builderDto.getGenerics()) { - method.addGenericParameter(genericParam); - } + method.setGenericParameters(builderDto.getGenerics()); method.addArgument("builderType", builderDto.getBuilderTypeName()); String targetFullName = builderDto.getBuildingTargetTypeName().getFullQualifiedName(); String builderSimpleName = builderDto.getBuilderTypeName().getClassName(); - JavadocDto javadoc = - new JavadocDto("Creating a new builder for {@code %s}.", targetFullName) - .addReturn("builder for {@code %s}", targetFullName); - // Add example to create() method - JavadocCodeBlockDto exampleBlock = new JavadocCodeBlockDto(); - exampleBlock.setCodeFormat( - "%s builder = %s.create();".formatted(builderSimpleName, builderSimpleName)); - javadoc.setExampleUsageCodeBlock(exampleBlock); - - method.setJavadoc(javadoc); + method.setJavadoc( + JavadocDtoBuilder.create() + .format("Creating a new builder for {@code %s}.", targetFullName) + .add2Tags( + new JavadocTagDto("return", "builder for {@code %s}".formatted(targetFullName))) + .exampleUsageCodeBlock( + e -> + e.codeFormat( + "%s builder = %s.create();" + .formatted(builderSimpleName, builderSimpleName))) + .build()); return method; } /** Creates the toString() method. */ protected BuilderMethodDto createToStringMethod(BuilderDefinitionDto builderDto) { - BuilderMethodDto method = new BuilderMethodDto("toString", TypeName.of(String.class)); - method.setOrdering(ORDERING_TO_STRING); - method.setPriority(BuilderMethodDto.PRIORITY_HIGHEST); - method.setModifier(AccessModifier.PUBLIC); - AnnotationDto overrideAnnotation = new AnnotationDto(); - overrideAnnotation.setAnnotationType(JavaLangMapper.map2TypeName(Override.class)); - method.addAnnotation(overrideAnnotation); + BuilderMethodDto method = + BuilderMethodDtoBuilder.create() + .methodName("toString") + .returnType(String.class) + .ordering(ORDERING_TO_STRING) + .priority(BuilderMethodDto.PRIORITY_HIGHEST) + .modifier(AccessModifier.PUBLIC) + .annotations(el -> el.annotationType(JavaLangMapper.map2TypeName(Override.class))) + .build(); // Create method implementation method.setCode( @@ -286,9 +296,11 @@ protected BuilderMethodDto createToStringMethod(BuilderDefinitionDto builderDto) method.getMethodCodeDto().addCodeBlockImport(toStringStyleType); method.setJavadoc( - new JavadocDto( + JavadocDtoBuilder.create() + .format( "Returns a string representation of this builder, including only fields that have been set.") - .addReturn("string representation of the builder")); + .add2Tags(new JavadocTagDto("return", "string representation of the builder")) + .build()); return method; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/GeneratedAnnotationEnhancer.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/GeneratedAnnotationEnhancer.java index acf745ea..8dbdcf68 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/GeneratedAnnotationEnhancer.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/GeneratedAnnotationEnhancer.java @@ -26,6 +26,7 @@ import javax.annotation.processing.Generated; import org.javahelpers.codegen.analysis.JavaLangMapper; 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.processor.generators.BuilderEnhancer; import org.javahelpers.simple.builders.processor.model.core.BuilderDefinitionDto; @@ -90,13 +91,13 @@ public void enhanceBuilder(BuilderDefinitionDto builderDto, BuilderProcessingCon * @return the annotation DTO for @Generated */ private AnnotationDto createGeneratedAnnotation() { - AnnotationDto annotation = new AnnotationDto(); - annotation.setAnnotationType(JavaLangMapper.map2TypeName(Generated.class)); - - // Add value member with processor class name (using the original name) - annotation.addMember( - "value", "\"Generated by org.javahelpers.simple.builders.processor.BuilderProcessor\""); - - return annotation; + return AnnotationDtoBuilder.create() + .annotationType(JavaLangMapper.map2TypeName(Generated.class)) + .members( + m -> + m.put( + "value", + "\"Generated by org.javahelpers.simple.builders.processor.BuilderProcessor\"")) + .build(); } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/JacksonAnnotationEnhancer.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/JacksonAnnotationEnhancer.java index 4ec4476a..f88581fb 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/JacksonAnnotationEnhancer.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/JacksonAnnotationEnhancer.java @@ -24,6 +24,7 @@ package org.javahelpers.simple.builders.processor.generators.builder; 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.processor.generators.BuilderEnhancer; import org.javahelpers.simple.builders.processor.model.core.BuilderDefinitionDto; @@ -113,18 +114,13 @@ private boolean isJacksonAvailable(BuilderProcessingContext context) { * @return the annotation DTO for @JsonPOJOBuilder */ private AnnotationDto createJsonPOJOBuilderAnnotation(BuilderDefinitionDto builderDto) { - AnnotationDto annotation = new AnnotationDto(); - annotation.setAnnotationType( - new TypeName("com.fasterxml.jackson.databind.annotation", "JsonPOJOBuilder")); - // Add withPrefix member with the setter prefix from configuration String setterPrefix = builderDto.getConfiguration().getSetterPrefix(); - if (setterPrefix != null) { - annotation.addMember("withPrefix", "\"" + setterPrefix + "\""); - } else { - annotation.addMember("withPrefix", "\"\""); - } - - return annotation; + return AnnotationDtoBuilder.create() + .annotationType( + new TypeName("com.fasterxml.jackson.databind.annotation", "JsonPOJOBuilder")) + .members( + m -> m.put("withPrefix", setterPrefix != null ? "\"" + setterPrefix + "\"" : "\"\"")) + .build(); } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/WithInterfaceEnhancer.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/WithInterfaceEnhancer.java index aa21a528..38185c4a 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/WithInterfaceEnhancer.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/builder/WithInterfaceEnhancer.java @@ -23,10 +23,11 @@ */ package org.javahelpers.simple.builders.processor.generators.builder; +import java.util.List; import org.javahelpers.codegen.analysis.JavaLangMapper; import org.javahelpers.codegen.enums.AccessModifier; -import org.javahelpers.codegen.model.javadoc.JavadocDto; -import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocTagDto; import org.javahelpers.codegen.model.type.NestedTypeDto; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameGeneric; @@ -34,7 +35,9 @@ import org.javahelpers.simple.builders.processor.generators.util.MethodGeneratorUtil; import org.javahelpers.simple.builders.processor.model.core.BuilderDefinitionDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; import org.javahelpers.simple.builders.processor.model.type.BuilderNestedTypeDto; +import org.javahelpers.simple.builders.processor.model.type.BuilderNestedTypeDtoBuilder; import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; /** @@ -112,23 +115,18 @@ public void enhanceBuilder(BuilderDefinitionDto builderDto, BuilderProcessingCon * @return the nested type DTO for the With interface */ private BuilderNestedTypeDto createWithInterface(BuilderDefinitionDto builderDto) { - BuilderNestedTypeDto withInterface = new BuilderNestedTypeDto(); - withInterface.setTypeName("With"); - withInterface.setKind(NestedTypeDto.NestedTypeKind.INTERFACE); - withInterface.setVisibility(AccessModifier.PUBLIC); - withInterface.setJavadoc( - new JavadocDto( - "Interface that can be implemented by the DTO to provide fluent modification methods.")); - - // Create the first method: DtoType with(Consumer b) - BuilderMethodDto withConsumerMethod = createWithConsumerMethod(builderDto); - withInterface.addMethod(withConsumerMethod); - - // Create the second method: BuilderType with() - BuilderMethodDto withBuilderMethod = createWithBuilderMethod(builderDto); - withInterface.addMethod(withBuilderMethod); - - return withInterface; + return BuilderNestedTypeDtoBuilder.create() + .typeName("With") + .kind(NestedTypeDto.NestedTypeKind.INTERFACE) + .visibility(AccessModifier.PUBLIC) + .javadoc( + j -> + j.format( + "Interface that can be implemented by the DTO to provide fluent modification methods.")) + // First method: DtoType with(Consumer b) + // Second method: BuilderType with() + .methods(List.of(createWithConsumerMethod(builderDto), createWithBuilderMethod(builderDto))) + .build(); } /** @@ -140,16 +138,16 @@ private BuilderNestedTypeDto createWithInterface(BuilderDefinitionDto builderDto private BuilderMethodDto createWithConsumerMethod(BuilderDefinitionDto builderDef) { // Return type is the DTO type TypeName dtoType = builderDef.getBuildingTargetTypeName(); - BuilderMethodDto method = new BuilderMethodDto("with", dtoType); - - // Parameter: Consumer b - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName("b"); // For interface methods, we store the full type as a string TypeNameGeneric consumerType = MethodGeneratorUtil.createConsumerType(builderDef.getBuilderTypeName()); - parameter.setParameterTypeName(consumerType); - method.addParameter(parameter); + BuilderMethodDto method = + BuilderMethodDtoBuilder.create() + .methodName("with") + .returnType(dtoType) + // Parameter: Consumer b + .parameters(el -> el.parameterName("b").parameterTypeName(consumerType)) + .build(); // Add implementation with validation to catch wrong implementations method.setCode( @@ -170,10 +168,12 @@ private BuilderMethodDto createWithConsumerMethod(BuilderDefinitionDto builderDe "illegalargumentexception", JavaLangMapper.map2TypeName(IllegalArgumentException.class)); method.setJavadoc( - new JavadocDto( + JavadocDtoBuilder.create() + .format( "Initializes a builder from an instance of this class, using methods of this builder to change values and returns the new built object.") - .addParam("b", "the consumer to apply modifications") - .addReturn("the modified instance")); + .add2Tags(new JavadocTagDto("param", "b the consumer to apply modifications")) + .add2Tags(new JavadocTagDto("return", "the modified instance")) + .build()); return method; } @@ -186,7 +186,11 @@ private BuilderMethodDto createWithConsumerMethod(BuilderDefinitionDto builderDe */ private BuilderMethodDto createWithBuilderMethod(BuilderDefinitionDto builderDef) { // Return type is the Builder type - BuilderMethodDto method = new BuilderMethodDto("with", builderDef.getBuilderTypeName()); + BuilderMethodDto method = + BuilderMethodDtoBuilder.create() + .methodName("with") + .returnType(builderDef.getBuilderTypeName()) + .build(); // Add implementation with validation to catch wrong implementations method.setCode( @@ -204,8 +208,11 @@ private BuilderMethodDto createWithBuilderMethod(BuilderDefinitionDto builderDef "illegalargumentexception", JavaLangMapper.map2TypeName(IllegalArgumentException.class)); method.setJavadoc( - new JavadocDto("Creates a builder initialized from this instance.") - .addReturn("a builder initialized with this instance's values")); + JavadocDtoBuilder.create() + .format("Creates a builder initialized from this instance.") + .add2Tags( + new JavadocTagDto("return", "a builder initialized with this instance's values")) + .build()); return method; } 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 80955302..3d8d0eee 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 @@ -31,8 +31,8 @@ import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; -import org.javahelpers.codegen.model.javadoc.JavadocDto; -import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocTagDto; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameList; import org.javahelpers.codegen.model.type.TypeNameSet; @@ -40,6 +40,7 @@ import org.javahelpers.simple.builders.processor.generators.util.JavadocConstants; import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; /** @@ -148,14 +149,13 @@ private BuilderMethodDto createAddToCollectionMethod( TypeName builderType, BuilderProcessingContext context) { String methodName = "add2" + StringUtils.capitalize(originalFieldName); - BuilderMethodDto methodDto = new BuilderMethodDto(methodName, builderType); - - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName("element"); - parameter.setParameterTypeName(elementType); - methodDto.addParameter(parameter); - - methodDto.setModifier(getMethodAccessModifier(context)); + BuilderMethodDto methodDto = + BuilderMethodDtoBuilder.create() + .methodName(methodName) + .returnType(builderType) + .parameters(el -> el.parameterName("element").parameterTypeName(elementType)) + .modifier(getMethodAccessModifier(context)) + .build(); String collectionImpl; TypeName collectionVarType; @@ -192,9 +192,11 @@ private BuilderMethodDto createAddToCollectionMethod( methodDto.setPriority(BuilderMethodDto.PRIORITY_MEDIUM); methodDto.setJavadoc( - new JavadocDto("Adds a single element to %s.", originalFieldName) - .addParam("element", "the element to add") - .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE)); + JavadocDtoBuilder.create() + .format("Adds a single element to %s.", originalFieldName) + .add2Tags(new JavadocTagDto("param", "element the element to add")) + .add2Tags(new JavadocTagDto("return", JavadocConstants.RETURN_BUILDER_INSTANCE)) + .build()); // 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. diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ArrayBuilderConsumerGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ArrayBuilderConsumerGenerator.java index 8e7627aa..8ad89e21 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ArrayBuilderConsumerGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ArrayBuilderConsumerGenerator.java @@ -28,8 +28,10 @@ import static org.javahelpers.simple.builders.processor.generators.util.MethodGeneratorUtil.*; import java.util.List; -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.MethodParameterDto; +import org.javahelpers.codegen.model.method.MethodParameterDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameArray; import org.javahelpers.codegen.model.type.TypeNameGeneric; @@ -127,9 +129,11 @@ private BuilderMethodDto createFieldConsumerWithArrayBuilder( TypeNameGeneric builderTypeGeneric = new TypeNameGeneric(collectionBuilderType, elementType); TypeNameGeneric consumerType = createConsumerType(builderTypeGeneric); - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName(fieldName + BUILDER_SUFFIX + SUFFIX_CONSUMER); - parameter.setParameterTypeName(consumerType); + MethodParameterDto parameter = + MethodParameterDtoBuilder.create() + .parameterName(fieldName + BUILDER_SUFFIX + SUFFIX_CONSUMER) + .parameterTypeName(consumerType) + .build(); BuilderMethodDto methodDto = createBuilderMethod(fieldName, returnBuilderType, context); methodDto.addParameter(parameter); @@ -171,10 +175,15 @@ private BuilderMethodDto createFieldConsumerWithArrayBuilder( methodDto.addArgument("elementType", elementType); methodDto.setPriority(BuilderMethodDto.PRIORITY_MEDIUM); methodDto.setJavadoc( - new JavadocDto( + JavadocDtoBuilder.create() + .format( "Sets the value for %s using the fluent builder consumer.", fieldName) - .addParam(parameter.getParameterName(), "consumer for %s", fieldName) - .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE)); + .add2Tags( + new JavadocTagDto( + "param", + parameter.getParameterName() + " " + "consumer for %s".formatted(fieldName))) + .add2Tags(new JavadocTagDto("return", JavadocConstants.RETURN_BUILDER_INSTANCE)) + .build()); 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 801156ed..04ee1625 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 @@ -28,8 +28,10 @@ import static org.javahelpers.simple.builders.processor.generators.util.MethodGeneratorUtil.*; import java.util.List; -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.MethodParameterDto; +import org.javahelpers.codegen.model.method.MethodParameterDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameArray; import org.javahelpers.codegen.model.type.TypeNameGeneric; @@ -115,9 +117,11 @@ private BuilderMethodDto createFieldSetterForArrayFromList( BuilderProcessingContext context) { String fieldName = field.getOriginalFieldName(); String fieldNameInBuilder = field.getFieldNameInBuilder(); - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName(fieldName); - parameter.setParameterTypeName(listType); + MethodParameterDto parameter = + MethodParameterDtoBuilder.create() + .parameterName(fieldName) + .parameterTypeName(listType) + .build(); BuilderMethodDto methodDto = createBuilderMethod(fieldName, builderType, context); methodDto.addParameter(parameter); @@ -143,9 +147,12 @@ private BuilderMethodDto createFieldSetterForArrayFromList( methodDto.setPriority(BuilderMethodDto.PRIORITY_HIGH); String fieldJavadocDesc = field.getJavaDocDescriptionOrFieldName(); methodDto.setJavadoc( - new JavadocDto("Sets the value for %s.", fieldName) - .addParam(parameter.getParameterName(), fieldJavadocDesc) - .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE)); + JavadocDtoBuilder.create() + .format("Sets the value for %s.", fieldName) + .add2Tags( + new JavadocTagDto("param", parameter.getParameterName() + " " + fieldJavadocDesc)) + .add2Tags(new JavadocTagDto("return", JavadocConstants.RETURN_BUILDER_INSTANCE)) + .build()); // Add example fragment for array conversion method addExampleChainFragment(methodDto, elementType, fieldName, context::resolveBuilderType); diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/StringBuilderConsumerGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/StringBuilderConsumerGenerator.java index 984823ee..2b8f6747 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/StringBuilderConsumerGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/StringBuilderConsumerGenerator.java @@ -30,8 +30,10 @@ import java.util.List; import java.util.Optional; -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.MethodParameterDto; +import org.javahelpers.codegen.model.method.MethodParameterDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameArray; import org.javahelpers.codegen.model.type.TypeNameGeneric; @@ -138,9 +140,11 @@ private BuilderMethodDto createStringBuilderConsumer( BuilderProcessingContext context) { TypeName stringBuilderType = map2TypeName(StringBuilder.class); TypeNameGeneric consumerType = createConsumerType(stringBuilderType); - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName(fieldName + "StringBuilderConsumer"); - parameter.setParameterTypeName(consumerType); + MethodParameterDto parameter = + MethodParameterDtoBuilder.create() + .parameterName(fieldName + "StringBuilderConsumer") + .parameterTypeName(consumerType) + .build(); BuilderMethodDto methodDto = createBuilderMethod(fieldName, builderType, context); methodDto.addParameter(parameter); methodDto.setCode( @@ -157,11 +161,17 @@ private BuilderMethodDto createStringBuilderConsumer( methodDto.setReturnType(builderType); methodDto.setPriority(BuilderMethodDto.PRIORITY_LOW); methodDto.setJavadoc( - new JavadocDto( + JavadocDtoBuilder.create() + .format( "Sets the value for %s by executing the provided consumer.", fieldName) - .addParam( - parameter.getParameterName(), "consumer providing an instance of %s", fieldJavadoc) - .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE)); + .add2Tags( + new JavadocTagDto( + "param", + parameter.getParameterName() + + " " + + "consumer providing an instance of %s".formatted(fieldJavadoc))) + .add2Tags(new JavadocTagDto("return", JavadocConstants.RETURN_BUILDER_INSTANCE)) + .build()); // Add example fragment for StringBuilder consumer method addExampleChainFragmentTemplate(methodDto, "#{methodName}(sb -> sb.append(\"text\"))"); diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/StringFormatHelperGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/StringFormatHelperGenerator.java index de525afc..7840d729 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/StringFormatHelperGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/StringFormatHelperGenerator.java @@ -34,8 +34,10 @@ import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.javahelpers.codegen.model.annotation.AnnotationDto; -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.MethodParameterDto; +import org.javahelpers.codegen.model.method.MethodParameterDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameArray; import org.javahelpers.codegen.model.type.TypeNameGeneric; @@ -172,16 +174,18 @@ private BuilderMethodDto createStringFormatMethodWithTransform( BuilderProcessingContext context) { TypeName stringType = map2TypeName(String.class); - MethodParameterDto formatParam = new MethodParameterDto(); - formatParam.setParameterName("format"); - formatParam.setParameterTypeName(stringType); - if (annotations != null) { - annotations.forEach(formatParam::addAnnotation); - } + MethodParameterDto formatParam = + MethodParameterDtoBuilder.create() + .parameterName("format") + .parameterTypeName(stringType) + .annotations(annotations != null ? annotations : List.of()) + .build(); - MethodParameterDto argsParam = new MethodParameterDto(); - argsParam.setParameterName("args"); - argsParam.setParameterTypeName(TypeNameArray.of(Object.class)); + MethodParameterDto argsParam = + MethodParameterDtoBuilder.create() + .parameterName("args") + .parameterTypeName(TypeNameArray.of(Object.class)) + .build(); BuilderMethodDto methodDto = createBuilderMethod(fieldName, builderType, context); methodDto.addParameter(formatParam); @@ -196,14 +200,17 @@ private BuilderMethodDto createStringFormatMethodWithTransform( methodDto.addArgument("builderFieldWrapper", TRACKED_VALUE_TYPE); methodDto.setPriority(BuilderMethodDto.PRIORITY_HIGH); methodDto.setJavadoc( - new JavadocDto( + JavadocDtoBuilder.create() + .format( "Sets the String value for %s by using String.format(format, args).\nSee {@link String#format(String, Object...)} for details.", fieldName) - .addParam(formatParam.getParameterName(), "A format string") - .addParam( - argsParam.getParameterName(), - "Arguments referenced by the format specifiers in the format string.") - .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE)); + .add2Tags(new JavadocTagDto("param", "format A format string")) + .add2Tags( + new JavadocTagDto( + "param", + "args Arguments referenced by the format specifiers in the format string.")) + .add2Tags(new JavadocTagDto("return", JavadocConstants.RETURN_BUILDER_INSTANCE)) + .build()); // Add example fragment for String format method addExampleChainFragmentTemplate(methodDto, "#{methodName}(\"Hello %s\", \"World\")"); 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 2296a6e6..a689a48f 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 @@ -33,8 +33,10 @@ import java.util.Collections; import java.util.List; import java.util.function.Supplier; -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.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.simple.builders.processor.generators.MethodGenerator; @@ -131,9 +133,11 @@ private BuilderMethodDto createFieldSupplier( TypeNameGeneric supplierType = new TypeNameGeneric(map2TypeName(Supplier.class), fieldType); String parameterName = fieldName + SUFFIX_SUPPLIER; - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName(parameterName); - parameter.setParameterTypeName(supplierType); + MethodParameterDto parameter = + MethodParameterDtoBuilder.create() + .parameterName(parameterName) + .parameterTypeName(supplierType) + .build(); BuilderMethodDto methodDto = createBuilderMethod(fieldName, builderType, context); methodDto.addParameter(parameter); @@ -149,10 +153,14 @@ private BuilderMethodDto createFieldSupplier( methodDto.setPriority(BuilderMethodDto.PRIORITY_HIGH); methodDto.setJavadoc( - new JavadocDto( + JavadocDtoBuilder.create() + .format( "Sets the value for %s by invoking the provided supplier.", fieldName) - .addParam(parameterName, "supplier for %s", fieldJavaDoc) - .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE)); + .add2Tags( + new JavadocTagDto( + "param", parameterName + " " + "supplier for %s".formatted(fieldJavaDoc))) + .add2Tags(new JavadocTagDto("return", JavadocConstants.RETURN_BUILDER_INSTANCE)) + .build()); addExampleChainFragmentWithSupplier( methodDto, fieldType, fieldName, context::resolveBuilderType); 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 7a27a13c..248b8365 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 @@ -45,9 +45,9 @@ import java.util.Set; import java.util.TreeSet; import java.util.function.UnaryOperator; -import org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDto; -import org.javahelpers.codegen.model.javadoc.JavadocDto; -import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocTagDto; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameGeneric; import org.javahelpers.codegen.model.type.TypeNamePrimitive; @@ -57,6 +57,7 @@ import org.javahelpers.simple.builders.processor.generators.util.JavadocConstants; import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; /** @@ -157,15 +158,13 @@ public List generateMethods( TypeNameGeneric updaterType = new TypeNameGeneric(map2TypeName(UnaryOperator.class), field.getFieldType()); - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName(parameterName); - parameter.setParameterTypeName(updaterType); - BuilderMethodDto methodDto = - new BuilderMethodDto( - generateBuilderMethodName(originalFieldName, context) + "Update", builderType); - methodDto.setModifier(getMethodAccessModifier(context)); - methodDto.addParameter(parameter); + BuilderMethodDtoBuilder.create() + .methodName(generateBuilderMethodName(originalFieldName, context) + "Update") + .returnType(builderType) + .parameters(el -> el.parameterName(parameterName).parameterTypeName(updaterType)) + .modifier(getMethodAccessModifier(context)) + .build(); methodDto.setCode( """ if (!this.$fieldName:N.isSet()) { @@ -191,14 +190,20 @@ The value must have been set before (directly or via an existing instance). .formatted(originalFieldName); description += builderConsumerGuidance(field, context); methodDto.setJavadoc( - new JavadocDto(description) - .addParam( - parameterName, - "operator applied to the current value; its result becomes the new value") - .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE) - .addThrows( - "IllegalStateException", - "if %s has not been set yet".formatted(originalFieldName))); + JavadocDtoBuilder.create() + .format(description) + .add2Tags( + new JavadocTagDto( + "param", + parameterName + + " operator applied to the current value; its result becomes the new value")) + .add2Tags(new JavadocTagDto("return", JavadocConstants.RETURN_BUILDER_INSTANCE)) + .add2Tags( + new JavadocTagDto( + "throws", + "IllegalStateException if %s has not been set yet" + .formatted(originalFieldName))) + .build()); addUpdateExample(methodDto, field, context); return Collections.singletonList(methodDto); @@ -246,15 +251,18 @@ private static void addUpdateExample( if (initialValue.isEmpty()) { return; } - JavadocCodeBlockDto methodExample = new JavadocCodeBlockDto(); - methodExample.setCodeFormat( - "builder.%s(%s).%s(%s);" - .formatted( - generateBuilderMethodName(field.getOriginalFieldName(), context), - initialValue.get(), - methodDto.getMethodName(), - updateExpression.get())); - methodDto.getJavadoc().setExampleUsageCodeBlock(methodExample); + methodDto + .getJavadoc() + .setExampleUsageCodeBlock( + JavadocCodeBlockDtoBuilder.create() + .codeFormat( + "builder.%s(%s).%s(%s);" + .formatted( + generateBuilderMethodName(field.getOriginalFieldName(), context), + initialValue.get(), + methodDto.getMethodName(), + updateExpression.get())) + .build()); } /** diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/integration/JacksonModuleGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/integration/JacksonModuleGenerator.java index ac12d998..8b1caf1b 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/integration/JacksonModuleGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/integration/JacksonModuleGenerator.java @@ -34,12 +34,14 @@ import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.enums.FormattingMode; import org.javahelpers.codegen.logging.ProcessingLogger; -import org.javahelpers.codegen.model.annotation.AnnotationDto; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; import org.javahelpers.codegen.model.integration.JacksonModuleEntryDto; 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.type.NestedTypeDto; +import org.javahelpers.codegen.model.type.NestedTypeDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.simple.builders.processor.model.core.BuilderConfiguration; import org.javahelpers.simple.builders.processor.model.core.BuilderDefinitionDto; @@ -168,11 +170,13 @@ public List getModuleDefinitions() { */ private GenerationTargetClassDto buildTargetClass( String packageName, Set entries, FormattingMode formattingMode) { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName(packageName, MODULE_CLASS_NAME)); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setSuperType(SIMPLE_MODULE_TYPE); - classDef.setFormattingMode(formattingMode); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName(packageName, MODULE_CLASS_NAME)) + .classAccessModifier(AccessModifier.PUBLIC) + .superType(SIMPLE_MODULE_TYPE) + .formattingMode(formattingMode) + .build(); // Each entry becomes a private nested mixin interface annotated with @JsonDeserialize. for (JacksonModuleEntryDto entry : entries) { @@ -188,22 +192,21 @@ private GenerationTargetClassDto buildTargetClass( } private static NestedTypeDto createMixinInterface(JacksonModuleEntryDto entry) { - NestedTypeDto mixin = new NestedTypeDto(); - mixin.setTypeName(entry.dtoType().getClassName() + "Mixin"); - mixin.setKind(NestedTypeDto.NestedTypeKind.INTERFACE); - mixin.setVisibility(AccessModifier.PRIVATE); - - AnnotationDto jsonDeserialize = new AnnotationDto(); - jsonDeserialize.setAnnotationType(JSON_DESERIALIZE_TYPE); - jsonDeserialize.addMember("builder", entry.generatedType().getClassName() + ".class"); - mixin.addAnnotation(jsonDeserialize); - - return mixin; + return NestedTypeDtoBuilder.create() + .typeName(entry.dtoType().getClassName() + "Mixin") + .kind(NestedTypeDto.NestedTypeKind.INTERFACE) + .visibility(AccessModifier.PRIVATE) + .annotations( + el -> + el.annotationType(JSON_DESERIALIZE_TYPE) + .members( + m -> m.put("builder", entry.generatedType().getClassName() + ".class"))) + .build(); } private static ConstructorDto createConstructor(Set entries) { - ConstructorDto constructor = new ConstructorDto(); - constructor.setVisibility(AccessModifier.PUBLIC); + ConstructorDto constructor = + ConstructorDtoBuilder.create().visibility(AccessModifier.PUBLIC).build(); MethodCodeDto code = new MethodCodeDto(); int index = 0; 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 74a9bf02..f8d18344 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 @@ -32,8 +32,10 @@ import org.apache.commons.lang3.StringUtils; import org.javahelpers.codegen.analysis.JavaLangMapper; import org.javahelpers.codegen.enums.AccessModifier; -import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocTagDto; 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.TypeName; import org.javahelpers.codegen.model.type.TypeNameGeneric; @@ -44,6 +46,7 @@ import org.javahelpers.codegen.util.JavadocExampleValues; import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; import org.javahelpers.simple.builders.processor.model.type.PrefillCall; import org.javahelpers.simple.builders.processor.model.type.ResolvedBuilder; import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; @@ -128,10 +131,11 @@ public static AccessModifier getMethodAccessModifier(BuilderProcessingContext co */ public static BuilderMethodDto createBuilderMethod( String fieldName, TypeName returnType, BuilderProcessingContext context) { - BuilderMethodDto method = - new BuilderMethodDto(generateBuilderMethodName(fieldName, context), returnType); - method.setModifier(getMethodAccessModifier(context)); - return method; + return BuilderMethodDtoBuilder.create() + .methodName(generateBuilderMethodName(fieldName, context)) + .returnType(returnType) + .modifier(getMethodAccessModifier(context)) + .build(); } /** @@ -178,13 +182,15 @@ public static BuilderMethodDto createBuilderMethodForFieldWithTransform( TypeName builderType, BuilderProcessingContext context) { - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName(field.getOriginalFieldName()); - parameter.setParameterTypeName(parameterType); - - if (field.getParameterAnnotations() != null) { - field.getParameterAnnotations().forEach(parameter::addAnnotation); - } + MethodParameterDto parameter = + MethodParameterDtoBuilder.create() + .parameterName(field.getOriginalFieldName()) + .parameterTypeName(parameterType) + .annotations( + field.getParameterAnnotations() != null + ? field.getParameterAnnotations() + : List.of()) + .build(); BuilderMethodDto methodDto = createBuilderMethod(field.getOriginalFieldName(), builderType, context); @@ -211,9 +217,12 @@ public static BuilderMethodDto createBuilderMethodForFieldWithTransform( String fieldJavadocDesc = field.getJavaDocDescriptionOrFieldName(); methodDto.setJavadoc( - new JavadocDto("Sets the value for %s.", field.getOriginalFieldName()) - .addParam(parameter.getParameterName(), fieldJavadocDesc) - .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE)); + JavadocDtoBuilder.create() + .format("Sets the value for %s.", field.getOriginalFieldName()) + .add2Tags( + new JavadocTagDto("param", parameter.getParameterName() + " " + fieldJavadocDesc)) + .add2Tags(new JavadocTagDto("return", JavadocConstants.RETURN_BUILDER_INSTANCE)) + .build()); return methodDto; } @@ -241,9 +250,11 @@ public static BuilderMethodDto createFieldConsumerWithBuilder( BuilderProcessingContext context) { TypeName fieldBuilderType = fieldBuilder.typeName(); TypeNameGeneric consumerType = createConsumerType(fieldBuilderType); - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName(field.getFieldNameInBuilder() + BUILDER_SUFFIX + SUFFIX_CONSUMER); - parameter.setParameterTypeName(consumerType); + MethodParameterDto parameter = + MethodParameterDtoBuilder.create() + .parameterName(field.getFieldNameInBuilder() + BUILDER_SUFFIX + SUFFIX_CONSUMER) + .parameterTypeName(consumerType) + .build(); BuilderMethodDto methodDto = createBuilderMethod(field.getOriginalFieldName(), parentBuilderType, context); methodDto.addParameter(parameter); @@ -277,14 +288,19 @@ public static BuilderMethodDto createFieldConsumerWithBuilder( methodDto.setPriority(BuilderMethodDto.PRIORITY_MEDIUM); String fieldJavadocDesc = field.getJavaDocDescriptionOrFieldName(); methodDto.setJavadoc( - new JavadocDto( + JavadocDtoBuilder.create() + .format( "Sets the value for %s using a builder consumer that produces the value.", field.getFieldNameInBuilder()) - .addParam( - parameter.getParameterName(), - "consumer providing an instance of a builder for %s", - fieldJavadocDesc) - .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE)); + .add2Tags( + new JavadocTagDto( + "param", + parameter.getParameterName() + + " " + + "consumer providing an instance of a builder for %s" + .formatted(fieldJavadocDesc))) + .add2Tags(new JavadocTagDto("return", JavadocConstants.RETURN_BUILDER_INSTANCE)) + .build()); return methodDto; } @@ -297,16 +313,15 @@ public static BuilderMethodDto createFieldConsumerWithBuilder( * @return the method DTO for the prefilling method */ public static BuilderMethodDto createFieldPrefillMethod(PrefillCall prefillCall) { - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName("value"); - parameter.setParameterTypeName(prefillCall.sourceType()); - BuilderMethodDto methodDto = new BuilderMethodDto(); - methodDto.setModifier(AccessModifier.PRIVATE); - methodDto.setStatic(true); - methodDto.setOrdering(2100); // last: private helpers go below toString - methodDto.setMethodName(prefillCall.methodName()); - methodDto.setReturnType(prefillCall.generatedType()); - methodDto.addParameter(parameter); + BuilderMethodDto methodDto = + BuilderMethodDtoBuilder.create() + .methodName(prefillCall.methodName()) + .returnType(prefillCall.generatedType()) + .modifier(AccessModifier.PRIVATE) + .isStatic(true) + .ordering(2100) // last: private helpers go below toString + .parameters(el -> el.parameterName("value").parameterTypeName(prefillCall.sourceType())) + .build(); StringBuilder code = new StringBuilder(); code.append("$builderType:T builder = ") .append(prefillCall.funcForEmptyInstance().instantiationCode("$builderType:T", "")) @@ -416,9 +431,11 @@ public static BuilderMethodDto createSimpleFieldConsumer( TypeName builderType, BuilderProcessingContext context) { TypeNameGeneric consumerType = createConsumerType(fieldType); - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName(field.getOriginalFieldName() + SUFFIX_CONSUMER); - parameter.setParameterTypeName(consumerType); + MethodParameterDto parameter = + MethodParameterDtoBuilder.create() + .parameterName(field.getOriginalFieldName() + SUFFIX_CONSUMER) + .parameterTypeName(consumerType) + .build(); BuilderMethodDto methodDto = createBuilderMethod(field.getOriginalFieldName(), builderType, context); @@ -441,14 +458,18 @@ public static BuilderMethodDto createSimpleFieldConsumer( String fieldJavadocDesc = field.getJavaDocDescriptionOrFieldName(); methodDto.setJavadoc( - new JavadocDto( + JavadocDtoBuilder.create() + .format( "Sets the value for %s by executing the provided consumer.", field.getOriginalFieldName()) - .addParam( - parameter.getParameterName(), - "consumer providing an instance of %s", - fieldJavadocDesc) - .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE)); + .add2Tags( + new JavadocTagDto( + "param", + parameter.getParameterName() + + " " + + "consumer providing an instance of %s".formatted(fieldJavadocDesc))) + .add2Tags(new JavadocTagDto("return", JavadocConstants.RETURN_BUILDER_INSTANCE)) + .build()); return methodDto; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java index 69505704..ea9821bc 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java @@ -28,6 +28,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.Optional; import org.javahelpers.codegen.model.annotation.AnnotationDto; import org.javahelpers.codegen.model.core.DeprecationInfoDto; @@ -40,7 +41,7 @@ * Definition of a field. Containing all information to generate methods in builder to set or modify * that field. */ -public class BuilderFieldDto { +public class BuilderFieldDto implements BuilderFieldDtoBuilder.With { /** Name of the field as it appears in the original DTO (used for method names and setters). */ private String originalFieldName; @@ -210,6 +211,18 @@ public void addMethod(BuilderMethodDto methodDto) { this.fieldSetterMethodsList.add(methodDto); } + /** + * Sets the methods of the field definition, replacing the current list. + * + * @param methods the methods to set + * @throws NullPointerException if methods is null + */ + public void setMethods(List methods) { + List copy = new ArrayList<>(Objects.requireNonNull(methods)); + this.fieldSetterMethodsList.clear(); + this.fieldSetterMethodsList.addAll(copy); + } + /** * Gets the original javadoc description extracted from the DTO. * diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDtoBuilder.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDtoBuilder.java new file mode 100644 index 00000000..84f7ed26 --- /dev/null +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDtoBuilder.java @@ -0,0 +1,1412 @@ +/* + * 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.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.List; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +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.core.DeprecationInfoDto; +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.codegen.model.type.TypeNameArray; +import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNameList; +import org.javahelpers.codegen.model.type.TypeNameMap; +import org.javahelpers.codegen.model.type.TypeNameSet; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; + +/** + * Builder for {@code org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto}. + * + *

This builder provides a fluent API for creating instances of + * org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto 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
+ * BuilderFieldDto result = BuilderFieldDtoBuilder.create()
+ *     .defaultValue("example defaultValue")
+ *     .defaultValue("Hello %s", "World")
+ *     .defaultValue(() -> "example defaultValue")
+ *     .defaultValue(sb -> sb.append("text"))
+ *     .fieldGenerics(List.of(GenericParameterDtoBuilder.create().build()))
+ *     .fieldGenerics(() -> List.of(GenericParameterDtoBuilder.create().build()))
+ *     .fieldGenerics(genericParameterDtoBuilder -> genericParameterDtoBuilder)
+ *     .fieldGenerics(GenericParameterDtoBuilder.create().build(), GenericParameterDtoBuilder.create().build())
+ *     .add2FieldGenerics(GenericParameterDtoBuilder.create().build())
+ *     .fieldNameInBuilder("example fieldNameInBuilder")
+ *     .fieldNameInBuilder("Hello %s", "World")
+ *     .fieldNameInBuilder(() -> "example fieldNameInBuilder")
+ *     .fieldNameInBuilder(sb -> sb.append("text"))
+ *     .getterInfo(GetterInfoDtoBuilder.create().build())
+ *     .getterInfo(() -> GetterInfoDtoBuilder.create().build())
+ *     .getterInfo(getterInfoDtoBuilder -> getterInfoDtoBuilder)
+ *     .javaDoc(new JavadocDto())
+ *     .javaDoc(JavadocDto::new)
+ *     .javaDoc(javadocDtoBuilder -> javadocDtoBuilder)
+ *     .nonNullable(true)
+ *     .nonNullable(() -> true)
+ *     .originalFieldName("example originalFieldName")
+ *     .originalFieldName("Hello %s", "World")
+ *     .originalFieldName(() -> "example originalFieldName")
+ *     .originalFieldName(sb -> sb.append("text"))
+ *     .originalJavaDocDescription("example originalJavaDocDescription")
+ *     .originalJavaDocDescription("Hello %s", "World")
+ *     .originalJavaDocDescription(() -> "example originalJavaDocDescription")
+ *     .originalJavaDocDescription(sb -> sb.append("text"))
+ *     .parameterAnnotations(List.of(AnnotationDtoBuilder.create().build()))
+ *     .parameterAnnotations(() -> List.of(AnnotationDtoBuilder.create().build()))
+ *     .parameterAnnotations(annotationDtoBuilder -> annotationDtoBuilder)
+ *     .parameterAnnotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build())
+ *     .add2ParameterAnnotations(AnnotationDtoBuilder.create().build())
+ *     .setterName("example setterName")
+ *     .setterName("Hello %s", "World")
+ *     .setterName(() -> "example setterName")
+ *     .setterName(sb -> sb.append("text"))
+ *     .build();
+ * }
+ */ +public class BuilderFieldDtoBuilder implements IBuilderBase { + + /** Tracked value for defaultValue: defaultValue. */ + private TrackedValue defaultValue = unsetValue(); + + /** Tracked value for deprecationInfo: deprecationInfo. */ + private TrackedValue deprecationInfo = unsetValue(); + + /** Tracked value for fieldGenerics: fieldGenerics. */ + private TrackedValue> fieldGenerics = unsetValue(); + + /** Tracked value for fieldNameInBuilder: fieldNameInBuilder. */ + private TrackedValue fieldNameInBuilder = unsetValue(); + + /** Tracked value for fieldType: fieldType. */ + private TrackedValue fieldType = unsetValue(); + + /** Tracked value for getterInfo: getterInfo. */ + private TrackedValue getterInfo = unsetValue(); + + /** Tracked value for javaDoc: javaDoc. */ + private TrackedValue javaDoc = unsetValue(); + + /** Tracked value for nonNullable: nonNullable. */ + private TrackedValue nonNullable = unsetValue(); + + /** Tracked value for originalFieldName: originalFieldName. */ + private TrackedValue originalFieldName = unsetValue(); + + /** Tracked value for originalJavaDocDescription: originalJavaDocDescription. */ + private TrackedValue originalJavaDocDescription = unsetValue(); + + /** Tracked value for parameterAnnotations: parameterAnnotations. */ + private TrackedValue> parameterAnnotations = unsetValue(); + + /** Tracked value for setterName: setterName. */ + private TrackedValue setterName = unsetValue(); + + private TrackedValue> methods = unsetValue(); + + /** + * Empty constructor of builder for {@code + * org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto}. + */ + public BuilderFieldDtoBuilder() {} + + /** + * Initialisation of builder for {@code + * org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto} by a instance. + * + * @param instance object instance for initialisiation + */ + public BuilderFieldDtoBuilder(BuilderFieldDto instance) { + this.deprecationInfo = initialValue(instance.getDeprecationInfo()); + this.fieldGenerics = initialValue(instance.getFieldGenerics()); + this.fieldNameInBuilder = initialValue(instance.getFieldNameInBuilder()); + this.fieldType = initialValue(instance.getFieldType()); + this.getterInfo = initialValue(instance.getGetterInfo()); + this.javaDoc = initialValue(instance.getJavaDoc()); + this.nonNullable = initialValue(instance.isNonNullable()); + this.originalFieldName = initialValue(instance.getOriginalFieldName()); + this.originalJavaDocDescription = initialValue(instance.getOriginalJavaDocDescription()); + this.parameterAnnotations = initialValue(instance.getParameterAnnotations()); + } + + /** + * Creating a new builder for {@code + * org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto}. + * + *

Example:

+ * + *
{@code
+   * BuilderFieldDtoBuilder builder = BuilderFieldDtoBuilder.create();
+   * }
+ * + * @return builder for {@code + * org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto} + */ + public static BuilderFieldDtoBuilder create() { + return new BuilderFieldDtoBuilder(); + } + + /** + * Sets the value for defaultValue by executing the provided consumer. + * + *

Generated from setter {@link BuilderFieldDto#setDefaultValue(String) setDefaultValue(String + * defaultValue)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setDefaultValue(String) setDefaultValue(String + * defaultValue)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setDefaultValue(String) setDefaultValue(String + * defaultValue)} + * + *

Example:

+ * + *
{@code
+   * builder.defaultValue("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 BuilderFieldDtoBuilder defaultValue(String format, Object... args) { + this.defaultValue = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for defaultValue. + * + *

Generated from setter {@link BuilderFieldDto#setDefaultValue(String) setDefaultValue(String + * defaultValue)} + * + *

Example:

+ * + *
{@code
+   * builder.defaultValue("example defaultValue");
+   * }
+ * + * @param defaultValue defaultValue + * @return current instance of builder + */ + public BuilderFieldDtoBuilder defaultValue(String defaultValue) { + this.defaultValue = changedValue(defaultValue); + return this; + } + + /** + * Sets the value for deprecationInfo by invoking the provided supplier. + * + *

Generated from setter {@link BuilderFieldDto#setDeprecationInfo(DeprecationInfoDto) + * setDeprecationInfo(DeprecationInfoDto deprecationInfo)} + * + * @param deprecationInfoSupplier supplier for deprecationInfo + * @return current instance of builder + */ + public BuilderFieldDtoBuilder deprecationInfo( + Supplier deprecationInfoSupplier) { + this.deprecationInfo = changedValue(deprecationInfoSupplier.get()); + return this; + } + + /** + * Sets the value for deprecationInfo. + * + *

Generated from setter {@link BuilderFieldDto#setDeprecationInfo(DeprecationInfoDto) + * setDeprecationInfo(DeprecationInfoDto deprecationInfo)} + * + * @param deprecationInfo deprecationInfo + * @return current instance of builder + */ + public BuilderFieldDtoBuilder deprecationInfo(DeprecationInfoDto deprecationInfo) { + this.deprecationInfo = changedValue(deprecationInfo); + return this; + } + + /** + * Adds a single element to fieldGenerics. + * + *

Generated from setter {@link BuilderFieldDto#setFieldGenerics(List) + * setFieldGenerics(List fieldGenerics)} + * + *

Example:

+ * + *
{@code
+   * builder.add2FieldGenerics(GenericParameterDtoBuilder.create().build());
+   * }
+ * + * @param element the element to add + * @return current instance of builder + */ + public BuilderFieldDtoBuilder add2FieldGenerics(GenericParameterDto element) { + List newCollection; + if (this.fieldGenerics.isSet()) { + newCollection = new ArrayList<>(this.fieldGenerics.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.fieldGenerics = changedValue(newCollection); + return this; + } + + /** + * Adds one element to fieldGenerics, configured through its builder. + * + * @param fieldGenericBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public BuilderFieldDtoBuilder fieldGenerics( + Consumer fieldGenericBuilderConsumer) { + GenericParameterDtoBuilder elementBuilder = new GenericParameterDtoBuilder(); + fieldGenericBuilderConsumer.accept(elementBuilder); + return add2FieldGenerics(elementBuilder.build()); + } + + /** + * Adds elements to fieldGenerics, each configured through its builder. + * + * @param fieldGenericBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final BuilderFieldDtoBuilder fieldGenerics( + Consumer... fieldGenericBuilderConsumers) { + for (Consumer consumer : fieldGenericBuilderConsumers) { + fieldGenerics(consumer); + } + return this; + } + + /** + * Sets the value for fieldGenerics by invoking the provided supplier. + * + *

Generated from setter {@link BuilderFieldDto#setFieldGenerics(List) + * setFieldGenerics(List fieldGenerics)} + * + *

Example:

+ * + *
{@code
+   * builder.fieldGenerics(() -> List.of(GenericParameterDtoBuilder.create().build()));
+   * }
+ * + * @param fieldGenericsSupplier supplier for fieldGenerics + * @return current instance of builder + */ + public BuilderFieldDtoBuilder fieldGenerics( + Supplier> fieldGenericsSupplier) { + this.fieldGenerics = changedValue(fieldGenericsSupplier.get()); + return this; + } + + /** + * Sets the value for fieldGenerics. + * + *

Generated from setter {@link BuilderFieldDto#setFieldGenerics(List) + * setFieldGenerics(List fieldGenerics)} + * + *

Example:

+ * + *
{@code
+   * builder.fieldGenerics(List.of(GenericParameterDtoBuilder.create().build()));
+   * }
+ * + * @param fieldGenerics fieldGenerics + * @return current instance of builder + */ + public BuilderFieldDtoBuilder fieldGenerics(List fieldGenerics) { + this.fieldGenerics = changedValue(fieldGenerics); + return this; + } + + /** + * Sets the value for fieldNameInBuilder by executing the provided consumer. + * + *

Generated from setter {@link BuilderFieldDto#setFieldNameInBuilder(String) + * setFieldNameInBuilder(String fieldNameInBuilder)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setFieldNameInBuilder(String) + * setFieldNameInBuilder(String fieldNameInBuilder)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setFieldNameInBuilder(String) + * setFieldNameInBuilder(String fieldNameInBuilder)} + * + *

Example:

+ * + *
{@code
+   * builder.fieldNameInBuilder("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 BuilderFieldDtoBuilder fieldNameInBuilder(String format, Object... args) { + this.fieldNameInBuilder = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for fieldNameInBuilder. + * + *

Generated from setter {@link BuilderFieldDto#setFieldNameInBuilder(String) + * setFieldNameInBuilder(String fieldNameInBuilder)} + * + *

Example:

+ * + *
{@code
+   * builder.fieldNameInBuilder("example fieldNameInBuilder");
+   * }
+ * + * @param fieldNameInBuilder fieldNameInBuilder + * @return current instance of builder + */ + public BuilderFieldDtoBuilder fieldNameInBuilder(String fieldNameInBuilder) { + this.fieldNameInBuilder = changedValue(fieldNameInBuilder); + return this; + } + + /** + * Sets the value for fieldType by invoking the provided supplier. + * + *

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

Generated from setter {@link BuilderFieldDto#setFieldType(TypeName) setFieldType(TypeName + * fieldType)} + * + * @param fieldType fieldType + * @return current instance of builder + */ + public BuilderFieldDtoBuilder fieldType(TypeName fieldType) { + this.fieldType = changedValue(fieldType); + return this; + } + + /** + * Sets fieldType to a TypeNameList built from the given list element type. + * + * @param elementClass the list element type + * @return fluent {@code builder} instance + */ + public BuilderFieldDtoBuilder fieldTypeList(Class elementClass) { + return fieldType(TypeNameList.of(elementClass)); + } + + /** + * Sets fieldType to a TypeNameList built from the given list element type. + * + * @param elementType the list element type + * @return fluent {@code builder} instance + */ + public BuilderFieldDtoBuilder fieldTypeList(TypeName elementType) { + return fieldType(TypeNameList.of(elementType)); + } + + /** + * Sets fieldType to a TypeNameSet built from the given set element type. + * + * @param elementClass the set element type + * @return fluent {@code builder} instance + */ + public BuilderFieldDtoBuilder fieldTypeSet(Class elementClass) { + return fieldType(TypeNameSet.of(elementClass)); + } + + /** + * Sets fieldType to a TypeNameSet built from the given set element type. + * + * @param elementType the set element type + * @return fluent {@code builder} instance + */ + public BuilderFieldDtoBuilder fieldTypeSet(TypeName elementType) { + return fieldType(TypeNameSet.of(elementType)); + } + + /** + * Sets fieldType to a TypeNameArray built from the given array component type. + * + * @param innerClass the array component type + * @return fluent {@code builder} instance + */ + public BuilderFieldDtoBuilder fieldTypeArray(Class innerClass) { + return fieldType(TypeNameArray.of(innerClass)); + } + + /** + * Sets fieldType to a TypeNameArray built from the given array component type. + * + * @param innerType the array component type + * @return fluent {@code builder} instance + */ + public BuilderFieldDtoBuilder fieldTypeArray(TypeName innerType) { + return fieldType(TypeNameArray.of(innerType)); + } + + /** + * Sets fieldType to a TypeNameGeneric built from the given generic outer type and + * type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public BuilderFieldDtoBuilder fieldTypeGeneric( + Class outerType, Class... innerTypeArguments) { + return fieldType(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets fieldType to a TypeNameGeneric built from the given generic outer type and + * type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public BuilderFieldDtoBuilder fieldTypeGeneric( + TypeName outerType, TypeName... innerTypeArguments) { + return fieldType(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets fieldType to a TypeNameMap built from the given map key and value types. + * + * @param keyClass the map key and value types + * @param valueClass the map key and value types + * @return fluent {@code builder} instance + */ + public BuilderFieldDtoBuilder fieldTypeMap(Class keyClass, Class valueClass) { + return fieldType(TypeNameMap.of(keyClass, valueClass)); + } + + /** + * Sets fieldType to a TypeNameMap built from the given map key and value types. + * + * @param keyType the map key and value types + * @param valueType the map key and value types + * @return fluent {@code builder} instance + */ + public BuilderFieldDtoBuilder fieldTypeMap(TypeName keyType, TypeName valueType) { + return fieldType(TypeNameMap.of(keyType, valueType)); + } + + /** + * Sets fieldType by class. + * + * @param fieldType the class to set as fieldType + * @return fluent {@code builder} instance + */ + public BuilderFieldDtoBuilder fieldType(Class fieldType) { + return fieldType(TypeName.of(fieldType)); + } + + /** + * Sets the value for fieldType from a package and simple class name. + * + * @param packageName package of the type + * @param className simple name of the type + * @return current instance of builder + */ + public BuilderFieldDtoBuilder fieldType(String packageName, String className) { + return fieldType(new TypeName(packageName, className)); + } + + /** + * Sets the value for getterInfo using a builder consumer that produces the value. + * + *

Generated from setter {@link BuilderFieldDto#setGetterInfo(GetterInfoDto) + * setGetterInfo(GetterInfoDto getterInfo)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setGetterInfo(GetterInfoDto) + * setGetterInfo(GetterInfoDto getterInfo)} + * + *

Example:

+ * + *
{@code
+   * builder.getterInfo(() -> GetterInfoDtoBuilder.create().build());
+   * }
+ * + * @param getterInfoSupplier supplier for getterInfo + * @return current instance of builder + */ + public BuilderFieldDtoBuilder getterInfo(Supplier getterInfoSupplier) { + this.getterInfo = changedValue(getterInfoSupplier.get()); + return this; + } + + /** + * Sets the value for getterInfo. + * + *

Generated from setter {@link BuilderFieldDto#setGetterInfo(GetterInfoDto) + * setGetterInfo(GetterInfoDto getterInfo)} + * + *

Example:

+ * + *
{@code
+   * builder.getterInfo(GetterInfoDtoBuilder.create().build());
+   * }
+ * + * @param getterInfo getterInfo + * @return current instance of builder + */ + public BuilderFieldDtoBuilder getterInfo(GetterInfoDto getterInfo) { + this.getterInfo = changedValue(getterInfo); + return this; + } + + /** + * Sets the value for javaDoc using a builder consumer that produces the value. + * + *

Generated from setter {@link BuilderFieldDto#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 BuilderFieldDtoBuilder 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 BuilderFieldDto#setJavaDoc(JavadocDto) setJavaDoc(JavadocDto + * javaDoc)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setJavaDoc(JavadocDto) setJavaDoc(JavadocDto + * javaDoc)} + * + *

Example:

+ * + *
{@code
+   * builder.javaDoc(new JavadocDto());
+   * }
+ * + * @param javaDoc javaDoc + * @return current instance of builder + */ + public BuilderFieldDtoBuilder javaDoc(JavadocDto javaDoc) { + this.javaDoc = changedValue(javaDoc); + return this; + } + + /** + * Sets the value for nonNullable by invoking the provided supplier. + * + *

Generated from setter {@link BuilderFieldDto#setNonNullable(boolean) setNonNullable(boolean + * nonNullable)} + * + *

Example:

+ * + *
{@code
+   * builder.nonNullable(() -> true);
+   * }
+ * + * @param nonNullableSupplier supplier for nonNullable + * @return current instance of builder + */ + public BuilderFieldDtoBuilder nonNullable(Supplier nonNullableSupplier) { + this.nonNullable = changedValue(nonNullableSupplier.get()); + return this; + } + + /** + * Sets the value for nonNullable. + * + *

Generated from setter {@link BuilderFieldDto#setNonNullable(boolean) setNonNullable(boolean + * nonNullable)} + * + *

Example:

+ * + *
{@code
+   * builder.nonNullable(true);
+   * }
+ * + * @param nonNullable nonNullable + * @return current instance of builder + */ + public BuilderFieldDtoBuilder nonNullable(boolean nonNullable) { + this.nonNullable = changedValue(nonNullable); + return this; + } + + /** + * Sets the value for originalFieldName by executing the provided consumer. + * + *

Generated from setter {@link BuilderFieldDto#setOriginalFieldName(String) + * setOriginalFieldName(String originalFieldName)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setOriginalFieldName(String) + * setOriginalFieldName(String originalFieldName)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setOriginalFieldName(String) + * setOriginalFieldName(String originalFieldName)} + * + *

Example:

+ * + *
{@code
+   * builder.originalFieldName("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 BuilderFieldDtoBuilder originalFieldName(String format, Object... args) { + this.originalFieldName = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for originalFieldName. + * + *

Generated from setter {@link BuilderFieldDto#setOriginalFieldName(String) + * setOriginalFieldName(String originalFieldName)} + * + *

Example:

+ * + *
{@code
+   * builder.originalFieldName("example originalFieldName");
+   * }
+ * + * @param originalFieldName originalFieldName + * @return current instance of builder + */ + public BuilderFieldDtoBuilder originalFieldName(String originalFieldName) { + this.originalFieldName = changedValue(originalFieldName); + return this; + } + + /** + * Sets the value for originalJavaDocDescription by executing the provided consumer. + * + *

Generated from setter {@link BuilderFieldDto#setOriginalJavaDocDescription(String) + * setOriginalJavaDocDescription(String originalJavaDocDescription)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setOriginalJavaDocDescription(String) + * setOriginalJavaDocDescription(String originalJavaDocDescription)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setOriginalJavaDocDescription(String) + * setOriginalJavaDocDescription(String originalJavaDocDescription)} + * + *

Example:

+ * + *
{@code
+   * builder.originalJavaDocDescription("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 BuilderFieldDtoBuilder originalJavaDocDescription(String format, Object... args) { + this.originalJavaDocDescription = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for originalJavaDocDescription. + * + *

Generated from setter {@link BuilderFieldDto#setOriginalJavaDocDescription(String) + * setOriginalJavaDocDescription(String originalJavaDocDescription)} + * + *

Example:

+ * + *
{@code
+   * builder.originalJavaDocDescription("example originalJavaDocDescription");
+   * }
+ * + * @param originalJavaDocDescription originalJavaDocDescription + * @return current instance of builder + */ + public BuilderFieldDtoBuilder originalJavaDocDescription(String originalJavaDocDescription) { + this.originalJavaDocDescription = changedValue(originalJavaDocDescription); + return this; + } + + /** + * Adds a single element to parameterAnnotations. + * + *

Generated from setter {@link BuilderFieldDto#setParameterAnnotations(List) + * setParameterAnnotations(List parameterAnnotations)} + * + *

Example:

+ * + *
{@code
+   * builder.add2ParameterAnnotations(AnnotationDtoBuilder.create().build());
+   * }
+ * + * @param element the element to add + * @return current instance of builder + */ + public BuilderFieldDtoBuilder add2ParameterAnnotations(AnnotationDto element) { + List newCollection; + if (this.parameterAnnotations.isSet()) { + newCollection = new ArrayList<>(this.parameterAnnotations.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.parameterAnnotations = changedValue(newCollection); + return this; + } + + /** + * Adds one annotation of the given type to 2ParameterAnnotations. + * + * @param annotationType the annotation type (not null) + * @return current instance of builder + */ + public BuilderFieldDtoBuilder add2ParameterAnnotations(Class annotationType) { + return add2ParameterAnnotations( + AnnotationDtoBuilder.create().annotationType(annotationType).build()); + } + + /** + * Adds one annotation of the given type to 2ParameterAnnotations. + * + * @param packageName package of the annotation type + * @param className simple name of the annotation type + * @return current instance of builder + */ + public BuilderFieldDtoBuilder add2ParameterAnnotations(String packageName, String className) { + return add2ParameterAnnotations( + AnnotationDtoBuilder.create().annotationType(packageName, className).build()); + } + + /** + * Adds one element to parameterAnnotations, configured through its builder. + * + * @param parameterAnnotationBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public BuilderFieldDtoBuilder parameterAnnotations( + Consumer parameterAnnotationBuilderConsumer) { + AnnotationDtoBuilder elementBuilder = AnnotationDtoBuilder.create(); + parameterAnnotationBuilderConsumer.accept(elementBuilder); + return add2ParameterAnnotations(elementBuilder.build()); + } + + /** + * Adds elements to parameterAnnotations, each configured through its builder. + * + * @param parameterAnnotationBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final BuilderFieldDtoBuilder parameterAnnotations( + Consumer... parameterAnnotationBuilderConsumers) { + for (Consumer consumer : parameterAnnotationBuilderConsumers) { + parameterAnnotations(consumer); + } + return this; + } + + /** + * Sets the value for parameterAnnotations by invoking the provided supplier. + * + *

Generated from setter {@link BuilderFieldDto#setParameterAnnotations(List) + * setParameterAnnotations(List parameterAnnotations)} + * + *

Example:

+ * + *
{@code
+   * builder.parameterAnnotations(() -> List.of(AnnotationDtoBuilder.create().build()));
+   * }
+ * + * @param parameterAnnotationsSupplier supplier for parameterAnnotations + * @return current instance of builder + */ + public BuilderFieldDtoBuilder parameterAnnotations( + Supplier> parameterAnnotationsSupplier) { + this.parameterAnnotations = changedValue(parameterAnnotationsSupplier.get()); + return this; + } + + /** + * Sets the value for parameterAnnotations. + * + *

Generated from setter {@link BuilderFieldDto#setParameterAnnotations(List) + * setParameterAnnotations(List parameterAnnotations)} + * + *

Example:

+ * + *
{@code
+   * builder.parameterAnnotations(List.of(AnnotationDtoBuilder.create().build()));
+   * }
+ * + * @param parameterAnnotations parameterAnnotations + * @return current instance of builder + */ + public BuilderFieldDtoBuilder parameterAnnotations(List parameterAnnotations) { + this.parameterAnnotations = changedValue(parameterAnnotations); + return this; + } + + /** + * Sets the value for setterName by executing the provided consumer. + * + *

Generated from setter {@link BuilderFieldDto#setSetterName(String) setSetterName(String + * setterName)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setSetterName(String) setSetterName(String + * setterName)} + * + *

Example:

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

Generated from setter {@link BuilderFieldDto#setSetterName(String) setSetterName(String + * setterName)} + * + *

Example:

+ * + *
{@code
+   * builder.setterName("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 BuilderFieldDtoBuilder setterName(String format, Object... args) { + this.setterName = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for setterName. + * + *

Generated from setter {@link BuilderFieldDto#setSetterName(String) setSetterName(String + * setterName)} + * + *

Example:

+ * + *
{@code
+   * builder.setterName("example setterName");
+   * }
+ * + * @param setterName setterName + * @return current instance of builder + */ + public BuilderFieldDtoBuilder setterName(String setterName) { + this.setterName = changedValue(setterName); + 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 BuilderFieldDtoBuilder 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 BuilderFieldDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Adds a single element to methods. + * + *

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

Example:

+ * + *
{@code
+   * builder.add2Methods(BuilderMethodDtoBuilder.create().build());
+   * }
+ * + * @param element the element to add + * @return current instance of builder + */ + public BuilderFieldDtoBuilder add2Methods(BuilderMethodDto 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; + } + + /** + * Adds one element to methods, configured through its builder. + * + * @param methodBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public BuilderFieldDtoBuilder methods(Consumer methodBuilderConsumer) { + BuilderMethodDtoBuilder elementBuilder = BuilderMethodDtoBuilder.create(); + methodBuilderConsumer.accept(elementBuilder); + return add2Methods(elementBuilder.build()); + } + + /** + * Adds elements to methods, each configured through its builder. + * + * @param methodBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final BuilderFieldDtoBuilder methods( + Consumer... methodBuilderConsumers) { + for (Consumer consumer : methodBuilderConsumers) { + methods(consumer); + } + return this; + } + + /** + * Sets the value for methods by invoking the provided supplier. + * + *

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

Example:

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

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

Example:

+ * + *
{@code
+   * builder.methods(List.of(BuilderMethodDtoBuilder.create().build()));
+   * }
+ * + * @param methods methods + * @return current instance of builder + */ + public BuilderFieldDtoBuilder methods(List methods) { + this.methods = changedValue(methods); + return this; + } + + /** + * Builds the configured DTO instance. + * + *

Example:

+ * + *
{@code
+   * BuilderFieldDto result = builder.build();
+   * }
+ */ + @Override + public BuilderFieldDto build() { + if (this.nonNullable.isSet() && this.nonNullable.value() == null) { + throw new IllegalStateException( + "Field 'nonNullable' is marked as non-null but null value was provided"); + } + BuilderFieldDto result = new BuilderFieldDto(); + this.defaultValue.ifSet(result::setDefaultValue); + this.deprecationInfo.ifSet(result::setDeprecationInfo); + this.fieldGenerics.ifSet(result::setFieldGenerics); + this.fieldNameInBuilder.ifSet(result::setFieldNameInBuilder); + this.fieldType.ifSet(result::setFieldType); + this.getterInfo.ifSet(result::setGetterInfo); + this.javaDoc.ifSet(result::setJavaDoc); + this.nonNullable.ifSet(result::setNonNullable); + this.originalFieldName.ifSet(result::setOriginalFieldName); + this.originalJavaDocDescription.ifSet(result::setOriginalJavaDocDescription); + this.parameterAnnotations.ifSet(result::setParameterAnnotations); + this.setterName.ifSet(result::setSetterName); + this.methods.ifSet(result::setMethods); + 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("defaultValue", this.defaultValue) + .append("deprecationInfo", this.deprecationInfo) + .append("fieldGenerics", this.fieldGenerics) + .append("fieldNameInBuilder", this.fieldNameInBuilder) + .append("fieldType", this.fieldType) + .append("getterInfo", this.getterInfo) + .append("javaDoc", this.javaDoc) + .append("nonNullable", this.nonNullable) + .append("originalFieldName", this.originalFieldName) + .append("originalJavaDocDescription", this.originalJavaDocDescription) + .append("parameterAnnotations", this.parameterAnnotations) + .append("setterName", this.setterName) + .append("methods", this.methods) + .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 BuilderFieldDto with(Consumer b) { + BuilderFieldDtoBuilder builder; + try { + builder = new BuilderFieldDtoBuilder(BuilderFieldDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'BuilderFieldDtoBuilder.With' should only be implemented by classes, which could be casted to 'BuilderFieldDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default BuilderFieldDtoBuilder with() { + try { + return new BuilderFieldDtoBuilder(BuilderFieldDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'BuilderFieldDtoBuilder.With' should only be implemented by classes, which could be casted to 'BuilderFieldDto'", + ex); + } + } + } +} diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderToGenerationTypeMapper.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderToGenerationTypeMapper.java index 3af20fe4..525d22f4 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderToGenerationTypeMapper.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderToGenerationTypeMapper.java @@ -30,13 +30,17 @@ import org.apache.commons.lang3.StringUtils; import org.javahelpers.codegen.model.core.ClassFieldDto; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; import org.javahelpers.codegen.model.method.ConstructorDto; import org.javahelpers.codegen.model.method.MethodCodePlaceholder; 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.type.NestedTypeDto; +import org.javahelpers.codegen.model.type.NestedTypeDtoBuilder; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; import org.javahelpers.simple.builders.processor.model.type.BuilderNestedTypeDto; @@ -87,33 +91,6 @@ public BuilderToGenerationTypeMapper(BuilderConfiguration configuration) { * @return the rendering DTO for code generation */ public GenerationTargetClassDto toRenderingDto(BuilderDefinitionDto builderDto) { - GenerationTargetClassDto renderingDto = new GenerationTargetClassDto(); - renderingDto.setTypeName(builderDto.getTypeName()); - renderingDto.setClassAccessModifier(builderDto.getClassAccessModifier()); - renderingDto.setSuperType(builderDto.getSuperType()); - renderingDto.setClassJavadoc( - configuration.shouldGenerateJavaDoc() ? builderDto.getClassJavadoc() : null); - renderingDto.setFormattingMode(configuration.formattingModeEnum()); - - builderDto.getClassFields().stream() - .map(this::toRenderingClassField) - .forEach(renderingDto::addClassField); - - builderDto.getConstructors().stream() - .map(this::toRenderingConstructor) - .forEach(renderingDto::addConstructor); - - builderDto.getGenerics().forEach(renderingDto::addGeneric); - - // Copy imports - builderDto.getImports().forEach(renderingDto::addImport); - - // Copy class annotations - builderDto.getClassAnnotations().forEach(renderingDto::addClassAnnotation); - - // Copy interfaces - builderDto.getInterfaces().forEach(renderingDto::addInterface); - // Map and copy methods in emission order (see METHOD_EMISSION_ORDER): field-originated // methods stay grouped per field, builder-level methods come after grouped ones. Stream fieldMethods = @@ -126,15 +103,26 @@ public GenerationTargetClassDto toRenderingDto(BuilderDefinitionDto builderDto) field -> field.getMethods().stream().map(method -> new FieldMethod(field, method))), builderDto.getMethods().stream().map(method -> new FieldMethod(null, method))); - fieldMethods - .sorted(METHOD_EMISSION_ORDER) - .forEach(pair -> renderingDto.addMethod(toMethodDto(pair.method()))); - - builderDto - .getNestedTypes() - .forEach(nestedType -> renderingDto.addNestedType(toNestedTypeDto(nestedType))); - - return renderingDto; + return GenerationTargetClassDtoBuilder.create() + .typeName(builderDto.getTypeName()) + .classAccessModifier(builderDto.getClassAccessModifier()) + .superType(builderDto.getSuperType()) + .classJavadoc(configuration.shouldGenerateJavaDoc() ? builderDto.getClassJavadoc() : null) + .formattingMode(configuration.formattingModeEnum()) + .classFields(builderDto.getClassFields().stream().map(this::toRenderingClassField).toList()) + .constructors( + builderDto.getConstructors().stream().map(this::toRenderingConstructor).toList()) + .generics(builderDto.getGenerics()) + .imports(builderDto.getImports()) + .classAnnotations(builderDto.getClassAnnotations()) + .interfaces(builderDto.getInterfaces()) + .methods( + fieldMethods + .sorted(METHOD_EMISSION_ORDER) + .map(pair -> toMethodDto(pair.method())) + .toList()) + .nestedTypes(builderDto.getNestedTypes().stream().map(this::toNestedTypeDto).toList()) + .build(); } /** @@ -148,16 +136,17 @@ public GenerationTargetClassDto toRenderingDto(BuilderDefinitionDto builderDto) * @return a new {@link MethodDto} with all rendering fields copied */ private MethodDto toMethodDto(BuilderMethodDto classMethod) { - MethodDto method = new MethodDto(classMethod.getMethodName(), classMethod.getReturnType()); - method.setModifier(classMethod.getModifier().orElse(null)); - method.setStatic(classMethod.isStatic()); - - if (configuration.shouldGenerateJavaDoc()) { - method.setJavadoc(buildMethodJavadoc(classMethod)); - } - classMethod.getAnnotations().forEach(method::addAnnotation); - classMethod.getParameters().forEach(method::addParameter); - classMethod.getGenericParameters().forEach(method::addGenericParameter); + MethodDto method = + MethodDtoBuilder.create() + .methodName(classMethod.getMethodName()) + .returnType(classMethod.getReturnType()) + .modifier(classMethod.getModifier().orElse(null)) + .isStatic(classMethod.isStatic()) + .javadoc(configuration.shouldGenerateJavaDoc() ? buildMethodJavadoc(classMethod) : null) + .annotations(classMethod.getAnnotations()) + .parameters(classMethod.getParameters()) + .genericParameters(classMethod.getGenericParameters()) + .build(); // Copy method code: set code format, copy all arguments, and preserve explicit code-block // imports @@ -307,7 +296,7 @@ private JavadocDto buildMethodJavadoc(BuilderMethodDto classMethod) { JavadocDto javadoc = classMethod.getJavadoc(); if (StringUtils.isNotBlank(classMethod.getSourceFieldName())) { if (javadoc == null) { - javadoc = new JavadocDto(); + javadoc = JavadocDtoBuilder.create().build(); } String sourceDescription = classMethod.getSourceDescription(); if (sourceDescription != null) { @@ -328,15 +317,13 @@ private JavadocDto buildMethodJavadoc(BuilderMethodDto classMethod) { * @return a new {@link NestedTypeDto} with all rendering fields copied */ public NestedTypeDto toNestedTypeDto(BuilderNestedTypeDto builderNestedType) { - NestedTypeDto nestedType = new NestedTypeDto(); - nestedType.setTypeName(builderNestedType.getTypeName()); - nestedType.setKind(builderNestedType.getKind()); - nestedType.setVisibility(builderNestedType.getVisibility()); - if (configuration.shouldGenerateJavaDoc()) { - nestedType.setJavadoc(builderNestedType.getJavadoc()); - } - builderNestedType.getAnnotations().forEach(nestedType::addAnnotation); - builderNestedType.getMethods().forEach(method -> nestedType.addMethod(toMethodDto(method))); - return nestedType; + return NestedTypeDtoBuilder.create() + .typeName(builderNestedType.getTypeName()) + .kind(builderNestedType.getKind()) + .visibility(builderNestedType.getVisibility()) + .javadoc(configuration.shouldGenerateJavaDoc() ? builderNestedType.getJavadoc() : null) + .annotations(builderNestedType.getAnnotations()) + .methods(builderNestedType.getMethods().stream().map(this::toMethodDto).toList()) + .build(); } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/GetterInfoDto.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/GetterInfoDto.java index 17df3f01..609190f2 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/GetterInfoDto.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/GetterInfoDto.java @@ -44,7 +44,8 @@ * @param getterName the simple name of the getter method; must not be {@code null} * @param deprecated whether the getter method is annotated {@code @Deprecated} */ -public record GetterInfoDto(String getterName, boolean deprecated) { +public record GetterInfoDto(String getterName, boolean deprecated) + implements GetterInfoDtoBuilder.With { /** * Compact constructor enforcing that {@code getterName} is non-null — a {@code GetterInfoDto} diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/GetterInfoDtoBuilder.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/GetterInfoDtoBuilder.java new file mode 100644 index 00000000..de580582 --- /dev/null +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/GetterInfoDtoBuilder.java @@ -0,0 +1,331 @@ +/* + * 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.model.core; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import org.apache.commons.lang3.builder.ToStringBuilder; +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.simple.builders.processor.model.core.GetterInfoDto}. + * + *

This builder provides a fluent API for creating instances of + * org.javahelpers.simple.builders.processor.model.core.GetterInfoDto 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
+ * GetterInfoDto result = GetterInfoDtoBuilder.create()
+ *     .getterName("example getterName")
+ *     .getterName("Hello %s", "World")
+ *     .getterName(() -> "example getterName")
+ *     .getterName(sb -> sb.append("text"))
+ *     .deprecated(true)
+ *     .deprecated(() -> true)
+ *     .build();
+ * }
+ */ +public class GetterInfoDtoBuilder implements IBuilderBase { + + /** Tracked value for getterName: getterName. */ + private TrackedValue getterName = unsetValue(); + + /** Tracked value for deprecated: deprecated. */ + private TrackedValue deprecated = unsetValue(); + + /** + * Empty constructor of builder for {@code + * org.javahelpers.simple.builders.processor.model.core.GetterInfoDto}. + */ + public GetterInfoDtoBuilder() {} + + /** + * Initialisation of builder for {@code + * org.javahelpers.simple.builders.processor.model.core.GetterInfoDto} by a instance. + * + * @param instance object instance for initialisiation + */ + public GetterInfoDtoBuilder(GetterInfoDto instance) { + this.getterName = initialValue(instance.getGetterName()); + this.deprecated = initialValue(instance.deprecated()); + } + + /** + * Creating a new builder for {@code + * org.javahelpers.simple.builders.processor.model.core.GetterInfoDto}. + * + *

Example:

+ * + *
{@code
+   * GetterInfoDtoBuilder builder = GetterInfoDtoBuilder.create();
+   * }
+ * + * @return builder for {@code org.javahelpers.simple.builders.processor.model.core.GetterInfoDto} + */ + public static GetterInfoDtoBuilder create() { + return new GetterInfoDtoBuilder(); + } + + /** + * Sets the value for deprecated by invoking the provided supplier. + * + *

Generated from parameter in constructor {@link GetterInfoDto#GetterInfoDto(String, boolean) + * GetterInfoDto(String getterName, boolean deprecated)} + * + *

Example:

+ * + *
{@code
+   * builder.deprecated(() -> true);
+   * }
+ * + * @param deprecatedSupplier supplier for deprecated + * @return current instance of builder + */ + public GetterInfoDtoBuilder deprecated(Supplier deprecatedSupplier) { + this.deprecated = changedValue(deprecatedSupplier.get()); + return this; + } + + /** + * Sets the value for deprecated. + * + *

Generated from parameter in constructor {@link GetterInfoDto#GetterInfoDto(String, boolean) + * GetterInfoDto(String getterName, boolean deprecated)} + * + *

Example:

+ * + *
{@code
+   * builder.deprecated(true);
+   * }
+ * + * @param deprecated deprecated + * @return current instance of builder + */ + public GetterInfoDtoBuilder deprecated(boolean deprecated) { + this.deprecated = changedValue(deprecated); + return this; + } + + /** + * Sets the value for getterName by executing the provided consumer. + * + *

Generated from parameter in constructor {@link GetterInfoDto#GetterInfoDto(String, boolean) + * GetterInfoDto(String getterName, boolean deprecated)} + * + *

Example:

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

Generated from parameter in constructor {@link GetterInfoDto#GetterInfoDto(String, boolean) + * GetterInfoDto(String getterName, boolean deprecated)} + * + *

Example:

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

Generated from parameter in constructor {@link GetterInfoDto#GetterInfoDto(String, boolean) + * GetterInfoDto(String getterName, boolean deprecated)} + * + *

Example:

+ * + *
{@code
+   * builder.getterName("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 GetterInfoDtoBuilder getterName(String format, Object... args) { + this.getterName = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for getterName. + * + *

Generated from parameter in constructor {@link GetterInfoDto#GetterInfoDto(String, boolean) + * GetterInfoDto(String getterName, boolean deprecated)} + * + *

Example:

+ * + *
{@code
+   * builder.getterName("example getterName");
+   * }
+ * + * @param getterName getterName + * @return current instance of builder + */ + public GetterInfoDtoBuilder getterName(String getterName) { + this.getterName = changedValue(getterName); + 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 GetterInfoDtoBuilder 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 GetterInfoDtoBuilder 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
+   * GetterInfoDto result = builder.build();
+   * }
+ */ + @Override + public GetterInfoDto build() { + if (!this.deprecated.isSet()) { + throw new IllegalStateException( + "Required field 'deprecated' must be set before calling build()"); + } + if (this.deprecated.value() == null) { + throw new IllegalStateException( + "Field 'deprecated' is marked as non-null but null value was provided"); + } + GetterInfoDto result = new GetterInfoDto(this.getterName.value(), this.deprecated.value()); + 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("getterName", this.getterName) + .append("deprecated", this.deprecated) + .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 GetterInfoDto with(Consumer b) { + GetterInfoDtoBuilder builder; + try { + builder = new GetterInfoDtoBuilder(GetterInfoDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'GetterInfoDtoBuilder.With' should only be implemented by classes, which could be casted to 'GetterInfoDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default GetterInfoDtoBuilder with() { + try { + return new GetterInfoDtoBuilder(GetterInfoDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'GetterInfoDtoBuilder.With' should only be implemented by classes, which could be casted to 'GetterInfoDto'", + ex); + } + } + } +} 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 cea81976..4e6c5e81 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 @@ -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; @@ -49,7 +50,7 @@ * org.javahelpers.simple.builders.processor.model.core.BuilderToGenerationTypeMapper} before being * added to {@code GenerationTargetClassDto}. */ -public class BuilderMethodDto { +public class BuilderMethodDto implements BuilderMethodDtoBuilder.With { // Priority constants for method conflict resolution (higher values win) public static final int PRIORITY_HIGHEST = 100; // Direct setters, with() methods public static final int PRIORITY_HIGH = 80; // Supplier, transform methods @@ -288,6 +289,20 @@ public void addParameter(MethodParameterDto paramDto) { this.parameters.add(paramDto); } + /** + * Sets the parameters of method, replacing the current list. + * + * @param parameters the parameters to set + * @throws NullPointerException if parameters is null + */ + public void setParameters(List parameters) { + Objects.requireNonNull(parameters); + if (parameters != this.parameters) { + this.parameters.clear(); + this.parameters.addAll(parameters); + } + } + /** * Getting a list of parameters of method. * @@ -307,6 +322,20 @@ public void addGenericParameter(GenericParameterDto genericParameter) { this.genericParameters.add(genericParameter); } + /** + * Sets the generic type parameters of method, replacing the current list. + * + * @param genericParameters the generic type parameters to set + * @throws NullPointerException if genericParameters is null + */ + public void setGenericParameters(List genericParameters) { + Objects.requireNonNull(genericParameters); + if (genericParameters != this.genericParameters) { + this.genericParameters.clear(); + this.genericParameters.addAll(genericParameters); + } + } + /** * Getting a list of generic type parameters of method. * @@ -424,6 +453,20 @@ public void addAnnotation(AnnotationDto annotation) { this.annotations.add(annotation); } + /** + * Sets the annotations of method, replacing the current list. + * + * @param annotations the annotations to set + * @throws NullPointerException if annotations is null + */ + public void setAnnotations(List annotations) { + Objects.requireNonNull(annotations); + if (annotations != this.annotations) { + this.annotations.clear(); + this.annotations.addAll(annotations); + } + } + /** * Returns the name of the source field this method was generated for. * diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/method/BuilderMethodDtoBuilder.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/method/BuilderMethodDtoBuilder.java new file mode 100644 index 00000000..20e4a91e --- /dev/null +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/method/BuilderMethodDtoBuilder.java @@ -0,0 +1,1464 @@ +/* + * 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.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 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.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.TypeName; +import org.javahelpers.codegen.model.type.TypeNameArray; +import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNameList; +import org.javahelpers.codegen.model.type.TypeNameMap; +import org.javahelpers.codegen.model.type.TypeNameSet; +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.simple.builders.processor.model.method.BuilderMethodDto}. + * + *

This builder provides a fluent API for creating instances of + * org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto 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
+ * BuilderMethodDto result = BuilderMethodDtoBuilder.create()
+ *     .methodName("example methodName")
+ *     .methodName("Hello %s", "World")
+ *     .methodName(() -> "example methodName")
+ *     .methodName(sb -> sb.append("text"))
+ *     .code("example code")
+ *     .code("Hello %s", "World")
+ *     .code(() -> "example code")
+ *     .code(sb -> sb.append("text"))
+ *     .constructorField(true)
+ *     .constructorField(() -> true)
+ *     .exampleChainFragment("example exampleChainFragment")
+ *     .exampleChainFragment("Hello %s", "World")
+ *     .exampleChainFragment(() -> "example exampleChainFragment")
+ *     .exampleChainFragment(sb -> sb.append("text"))
+ *     .javadoc(new JavadocDto())
+ *     .javadoc(JavadocDto::new)
+ *     .javadoc(javadocDtoBuilder -> javadocDtoBuilder)
+ *     .ordering(42)
+ *     .ordering(() -> 42)
+ *     .priority(42)
+ *     .priority(() -> 42)
+ *     .sourceDescription("example sourceDescription")
+ *     .sourceDescription("Hello %s", "World")
+ *     .sourceDescription(() -> "example sourceDescription")
+ *     .sourceDescription(sb -> sb.append("text"))
+ *     .sourceFieldName("example sourceFieldName")
+ *     .sourceFieldName("Hello %s", "World")
+ *     .sourceFieldName(() -> "example sourceFieldName")
+ *     .sourceFieldName(sb -> sb.append("text"))
+ *     .isStatic(true)
+ *     .isStatic(() -> true)
+ *     .build();
+ * }
+ */ +public class BuilderMethodDtoBuilder implements IBuilderBase { + + /** Tracked value for methodName: methodName. */ + private TrackedValue methodName = unsetValue(); + + /** Tracked value for returnType: returnType. */ + private TrackedValue returnType = unsetValue(); + + /** Tracked value for code: code. */ + private TrackedValue code = unsetValue(); + + /** Tracked value for constructorField: constructorField. */ + private TrackedValue constructorField = unsetValue(); + + /** Tracked value for exampleChainFragment: exampleChainFragment. */ + private TrackedValue exampleChainFragment = unsetValue(); + + /** Tracked value for javadoc: javadoc. */ + private TrackedValue javadoc = unsetValue(); + + /** Tracked value for modifier: modifier. */ + private TrackedValue modifier = unsetValue(); + + /** Tracked value for ordering: ordering. */ + private TrackedValue ordering = unsetValue(); + + /** Tracked value for priority: priority. */ + private TrackedValue priority = unsetValue(); + + /** Tracked value for sourceDescription: sourceDescription. */ + private TrackedValue sourceDescription = unsetValue(); + + /** Tracked value for sourceFieldName: sourceFieldName. */ + private TrackedValue sourceFieldName = unsetValue(); + + /** Tracked value for isStatic: isStatic. */ + private TrackedValue isStatic = unsetValue(); + + private TrackedValue> parameters = unsetValue(); + private TrackedValue> genericParameters = unsetValue(); + private TrackedValue> annotations = unsetValue(); + + /** + * Empty constructor of builder for {@code + * org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto}. + */ + public BuilderMethodDtoBuilder() {} + + /** + * Initialisation of builder for {@code + * org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto} by a instance. + * + * @param instance object instance for initialisiation + */ + public BuilderMethodDtoBuilder(BuilderMethodDto instance) { + this.methodName = initialValue(instance.getMethodName()); + this.returnType = initialValue(instance.getReturnType()); + this.constructorField = initialValue(instance.isConstructorField()); + this.exampleChainFragment = initialValue(instance.getExampleChainFragment()); + this.javadoc = initialValue(instance.getJavadoc()); + this.ordering = initialValue(instance.getOrdering()); + this.priority = initialValue(instance.getPriority()); + this.sourceDescription = initialValue(instance.getSourceDescription()); + this.sourceFieldName = initialValue(instance.getSourceFieldName()); + this.isStatic = initialValue(instance.isStatic()); + } + + /** + * Creating a new builder for {@code + * org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto}. + * + *

Example:

+ * + *
{@code
+   * BuilderMethodDtoBuilder builder = BuilderMethodDtoBuilder.create();
+   * }
+ * + * @return builder for {@code + * org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto} + */ + public static BuilderMethodDtoBuilder create() { + return new BuilderMethodDtoBuilder(); + } + + /** + * Sets the value for code by executing the provided consumer. + * + *

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

Example:

+ * + *
{@code
+   * builder.code(sb -> sb.append("text"));
+   * }
+ * + * @param codeStringBuilderConsumer consumer providing an instance of code + * @return current instance of builder + */ + public BuilderMethodDtoBuilder 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 BuilderMethodDto#setCode(String) setCode(String code)} + * + *

Example:

+ * + *
{@code
+   * builder.code(() -> "example code");
+   * }
+ * + * @param codeSupplier supplier for code + * @return current instance of builder + */ + public BuilderMethodDtoBuilder 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 BuilderMethodDto#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 BuilderMethodDtoBuilder code(String format, Object... args) { + this.code = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for code. + * + *

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

Example:

+ * + *
{@code
+   * builder.code("example code");
+   * }
+ * + * @param code code + * @return current instance of builder + */ + public BuilderMethodDtoBuilder code(String code) { + this.code = changedValue(code); + return this; + } + + /** + * Sets the value for constructorField by invoking the provided supplier. + * + *

Generated from setter {@link BuilderMethodDto#setConstructorField(boolean) + * setConstructorField(boolean constructorField)} + * + *

Example:

+ * + *
{@code
+   * builder.constructorField(() -> true);
+   * }
+ * + * @param constructorFieldSupplier supplier for constructorField + * @return current instance of builder + */ + public BuilderMethodDtoBuilder constructorField(Supplier constructorFieldSupplier) { + this.constructorField = changedValue(constructorFieldSupplier.get()); + return this; + } + + /** + * Sets the value for constructorField. + * + *

Generated from setter {@link BuilderMethodDto#setConstructorField(boolean) + * setConstructorField(boolean constructorField)} + * + *

Example:

+ * + *
{@code
+   * builder.constructorField(true);
+   * }
+ * + * @param constructorField constructorField + * @return current instance of builder + */ + public BuilderMethodDtoBuilder constructorField(boolean constructorField) { + this.constructorField = changedValue(constructorField); + return this; + } + + /** + * Sets the value for exampleChainFragment by executing the provided consumer. + * + *

Generated from setter {@link BuilderMethodDto#setExampleChainFragment(String) + * setExampleChainFragment(String exampleChainFragment)} + * + *

Example:

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

Generated from setter {@link BuilderMethodDto#setExampleChainFragment(String) + * setExampleChainFragment(String exampleChainFragment)} + * + *

Example:

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

Generated from setter {@link BuilderMethodDto#setExampleChainFragment(String) + * setExampleChainFragment(String exampleChainFragment)} + * + *

Example:

+ * + *
{@code
+   * builder.exampleChainFragment("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 BuilderMethodDtoBuilder exampleChainFragment(String format, Object... args) { + this.exampleChainFragment = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for exampleChainFragment. + * + *

Generated from setter {@link BuilderMethodDto#setExampleChainFragment(String) + * setExampleChainFragment(String exampleChainFragment)} + * + *

Example:

+ * + *
{@code
+   * builder.exampleChainFragment("example exampleChainFragment");
+   * }
+ * + * @param exampleChainFragment exampleChainFragment + * @return current instance of builder + */ + public BuilderMethodDtoBuilder exampleChainFragment(String exampleChainFragment) { + this.exampleChainFragment = changedValue(exampleChainFragment); + return this; + } + + /** + * Sets the value for isStatic by invoking the provided supplier. + * + *

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

Example:

+ * + *
{@code
+   * builder.isStatic(() -> true);
+   * }
+ * + * @param isStaticSupplier supplier for isStatic + * @return current instance of builder + */ + public BuilderMethodDtoBuilder isStatic(Supplier isStaticSupplier) { + this.isStatic = changedValue(isStaticSupplier.get()); + return this; + } + + /** + * Sets the value for isStatic. + * + *

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

Example:

+ * + *
{@code
+   * builder.isStatic(true);
+   * }
+ * + * @param isStatic isStatic + * @return current instance of builder + */ + public BuilderMethodDtoBuilder isStatic(boolean isStatic) { + this.isStatic = changedValue(isStatic); + return this; + } + + /** + * Sets the value for javadoc using a builder consumer that produces the value. + * + *

Generated from setter {@link BuilderMethodDto#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 BuilderMethodDtoBuilder 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 BuilderMethodDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

Example:

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

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

Example:

+ * + *
{@code
+   * builder.javadoc(new JavadocDto());
+   * }
+ * + * @param javadoc javadoc + * @return current instance of builder + */ + public BuilderMethodDtoBuilder javadoc(JavadocDto javadoc) { + this.javadoc = changedValue(javadoc); + return this; + } + + /** + * Sets the value for methodName by executing the provided consumer. + * + *

Generated from parameter in constructor {@link BuilderMethodDto#BuilderMethodDto(String, + * TypeName) BuilderMethodDto(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 BuilderMethodDtoBuilder 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 BuilderMethodDto#BuilderMethodDto(String, + * TypeName) BuilderMethodDto(String methodName, TypeName returnType)} + * + *

Example:

+ * + *
{@code
+   * builder.methodName(() -> "example methodName");
+   * }
+ * + * @param methodNameSupplier supplier for methodName + * @return current instance of builder + */ + public BuilderMethodDtoBuilder 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 BuilderMethodDto#BuilderMethodDto(String, + * TypeName) BuilderMethodDto(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 BuilderMethodDtoBuilder 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 BuilderMethodDto#BuilderMethodDto(String, + * TypeName) BuilderMethodDto(String methodName, TypeName returnType)} + * + *

Example:

+ * + *
{@code
+   * builder.methodName("example methodName");
+   * }
+ * + * @param methodName methodName + * @return current instance of builder + */ + public BuilderMethodDtoBuilder methodName(String methodName) { + this.methodName = changedValue(methodName); + return this; + } + + /** + * Sets the value for modifier by invoking the provided supplier. + * + *

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

Generated from setter {@link BuilderMethodDto#setModifier(AccessModifier) + * setModifier(AccessModifier modifier)} + * + * @param modifier modifier + * @return current instance of builder + */ + public BuilderMethodDtoBuilder modifier(AccessModifier modifier) { + this.modifier = changedValue(modifier); + return this; + } + + /** + * Sets the value for ordering by invoking the provided supplier. + * + *

Generated from setter {@link BuilderMethodDto#setOrdering(int) setOrdering(int ordering)} + * + *

Example:

+ * + *
{@code
+   * builder.ordering(() -> 42);
+   * }
+ * + * @param orderingSupplier supplier for ordering + * @return current instance of builder + */ + public BuilderMethodDtoBuilder ordering(Supplier orderingSupplier) { + this.ordering = changedValue(orderingSupplier.get()); + return this; + } + + /** + * Sets the value for ordering. + * + *

Generated from setter {@link BuilderMethodDto#setOrdering(int) setOrdering(int ordering)} + * + *

Example:

+ * + *
{@code
+   * builder.ordering(42);
+   * }
+ * + * @param ordering ordering + * @return current instance of builder + */ + public BuilderMethodDtoBuilder ordering(int ordering) { + this.ordering = changedValue(ordering); + return this; + } + + /** + * Sets the value for priority by invoking the provided supplier. + * + *

Generated from setter {@link BuilderMethodDto#setPriority(int) setPriority(int priority)} + * + *

Example:

+ * + *
{@code
+   * builder.priority(() -> 42);
+   * }
+ * + * @param prioritySupplier supplier for priority + * @return current instance of builder + */ + public BuilderMethodDtoBuilder priority(Supplier prioritySupplier) { + this.priority = changedValue(prioritySupplier.get()); + return this; + } + + /** + * Sets the value for priority. + * + *

Generated from setter {@link BuilderMethodDto#setPriority(int) setPriority(int priority)} + * + *

Example:

+ * + *
{@code
+   * builder.priority(42);
+   * }
+ * + * @param priority priority + * @return current instance of builder + */ + public BuilderMethodDtoBuilder priority(int priority) { + this.priority = changedValue(priority); + return this; + } + + /** + * Sets the value for returnType by invoking the provided supplier. + * + *

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

Generated from parameter in constructor {@link BuilderMethodDto#BuilderMethodDto(String, + * TypeName) BuilderMethodDto(String methodName, TypeName returnType)} + * + * @param returnType returnType + * @return current instance of builder + */ + public BuilderMethodDtoBuilder returnType(TypeName returnType) { + this.returnType = changedValue(returnType); + return this; + } + + /** + * Sets returnType to a TypeNameList built from the given list element type. + * + * @param elementClass the list element type + * @return fluent {@code builder} instance + */ + public BuilderMethodDtoBuilder returnTypeList(Class elementClass) { + return returnType(TypeNameList.of(elementClass)); + } + + /** + * Sets returnType to a TypeNameList built from the given list element type. + * + * @param elementType the list element type + * @return fluent {@code builder} instance + */ + public BuilderMethodDtoBuilder returnTypeList(TypeName elementType) { + return returnType(TypeNameList.of(elementType)); + } + + /** + * Sets returnType to a TypeNameSet built from the given set element type. + * + * @param elementClass the set element type + * @return fluent {@code builder} instance + */ + public BuilderMethodDtoBuilder returnTypeSet(Class elementClass) { + return returnType(TypeNameSet.of(elementClass)); + } + + /** + * Sets returnType to a TypeNameSet built from the given set element type. + * + * @param elementType the set element type + * @return fluent {@code builder} instance + */ + public BuilderMethodDtoBuilder returnTypeSet(TypeName elementType) { + return returnType(TypeNameSet.of(elementType)); + } + + /** + * Sets returnType to a TypeNameArray built from the given array component type. + * + * @param innerClass the array component type + * @return fluent {@code builder} instance + */ + public BuilderMethodDtoBuilder returnTypeArray(Class innerClass) { + return returnType(TypeNameArray.of(innerClass)); + } + + /** + * Sets returnType to a TypeNameArray built from the given array component type. + * + * @param innerType the array component type + * @return fluent {@code builder} instance + */ + public BuilderMethodDtoBuilder returnTypeArray(TypeName innerType) { + return returnType(TypeNameArray.of(innerType)); + } + + /** + * Sets returnType to a TypeNameGeneric built from the given generic outer type and + * type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public BuilderMethodDtoBuilder returnTypeGeneric( + Class outerType, Class... innerTypeArguments) { + return returnType(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets returnType to a TypeNameGeneric built from the given generic outer type and + * type arguments. + * + * @param outerType the generic outer type and type arguments + * @param innerTypeArguments the generic outer type and type arguments + * @return fluent {@code builder} instance + */ + public BuilderMethodDtoBuilder returnTypeGeneric( + TypeName outerType, TypeName... innerTypeArguments) { + return returnType(TypeNameGeneric.of(outerType, innerTypeArguments)); + } + + /** + * Sets returnType to a TypeNameMap built from the given map key and value types. + * + * @param keyClass the map key and value types + * @param valueClass the map key and value types + * @return fluent {@code builder} instance + */ + public BuilderMethodDtoBuilder returnTypeMap(Class keyClass, Class valueClass) { + return returnType(TypeNameMap.of(keyClass, valueClass)); + } + + /** + * Sets returnType to a TypeNameMap built from the given map key and value types. + * + * @param keyType the map key and value types + * @param valueType the map key and value types + * @return fluent {@code builder} instance + */ + public BuilderMethodDtoBuilder returnTypeMap(TypeName keyType, TypeName valueType) { + return returnType(TypeNameMap.of(keyType, valueType)); + } + + /** + * Sets returnType by class. + * + * @param returnType the class to set as returnType + * @return fluent {@code builder} instance + */ + public BuilderMethodDtoBuilder returnType(Class returnType) { + return returnType(TypeName.of(returnType)); + } + + /** + * Sets the value for returnType from a package and simple class name. + * + * @param packageName package of the type + * @param className simple name of the type + * @return current instance of builder + */ + public BuilderMethodDtoBuilder returnType(String packageName, String className) { + return returnType(new TypeName(packageName, className)); + } + + /** + * Sets the value for sourceDescription by executing the provided consumer. + * + *

Generated from setter {@link BuilderMethodDto#setSourceDescription(String) + * setSourceDescription(String sourceDescription)} + * + *

Example:

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

Generated from setter {@link BuilderMethodDto#setSourceDescription(String) + * setSourceDescription(String sourceDescription)} + * + *

Example:

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

Generated from setter {@link BuilderMethodDto#setSourceDescription(String) + * setSourceDescription(String sourceDescription)} + * + *

Example:

+ * + *
{@code
+   * builder.sourceDescription("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 BuilderMethodDtoBuilder sourceDescription(String format, Object... args) { + this.sourceDescription = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for sourceDescription. + * + *

Generated from setter {@link BuilderMethodDto#setSourceDescription(String) + * setSourceDescription(String sourceDescription)} + * + *

Example:

+ * + *
{@code
+   * builder.sourceDescription("example sourceDescription");
+   * }
+ * + * @param sourceDescription sourceDescription + * @return current instance of builder + */ + public BuilderMethodDtoBuilder sourceDescription(String sourceDescription) { + this.sourceDescription = changedValue(sourceDescription); + return this; + } + + /** + * Sets the value for sourceFieldName by executing the provided consumer. + * + *

Generated from setter {@link BuilderMethodDto#setSourceFieldName(String) + * setSourceFieldName(String sourceFieldName)} + * + *

Example:

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

Generated from setter {@link BuilderMethodDto#setSourceFieldName(String) + * setSourceFieldName(String sourceFieldName)} + * + *

Example:

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

Generated from setter {@link BuilderMethodDto#setSourceFieldName(String) + * setSourceFieldName(String sourceFieldName)} + * + *

Example:

+ * + *
{@code
+   * builder.sourceFieldName("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 BuilderMethodDtoBuilder sourceFieldName(String format, Object... args) { + this.sourceFieldName = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for sourceFieldName. + * + *

Generated from setter {@link BuilderMethodDto#setSourceFieldName(String) + * setSourceFieldName(String sourceFieldName)} + * + *

Example:

+ * + *
{@code
+   * builder.sourceFieldName("example sourceFieldName");
+   * }
+ * + * @param sourceFieldName sourceFieldName + * @return current instance of builder + */ + public BuilderMethodDtoBuilder sourceFieldName(String sourceFieldName) { + this.sourceFieldName = changedValue(sourceFieldName); + 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 BuilderMethodDtoBuilder 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 BuilderMethodDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Adds a single element to parameters. + * + *

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

Example:

+ * + *
{@code
+   * builder.add2Parameters(MethodParameterDtoBuilder.create().build());
+   * }
+ * + * @param element the element to add + * @return current instance of builder + */ + public BuilderMethodDtoBuilder 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; + } + + /** + * Adds one element to parameters, configured through its builder. + * + * @param parameterBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public BuilderMethodDtoBuilder parameters( + Consumer parameterBuilderConsumer) { + MethodParameterDtoBuilder elementBuilder = new MethodParameterDtoBuilder(); + parameterBuilderConsumer.accept(elementBuilder); + return add2Parameters(elementBuilder.build()); + } + + /** + * Adds elements to parameters, each configured through its builder. + * + * @param parameterBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final BuilderMethodDtoBuilder parameters( + Consumer... parameterBuilderConsumers) { + for (Consumer consumer : parameterBuilderConsumers) { + parameters(consumer); + } + return this; + } + + /** + * Sets the value for parameters by invoking the provided supplier. + * + *

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

Example:

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

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

Example:

+ * + *
{@code
+   * builder.parameters(List.of(MethodParameterDtoBuilder.create().build()));
+   * }
+ * + * @param parameters parameters + * @return current instance of builder + */ + public BuilderMethodDtoBuilder parameters(List parameters) { + this.parameters = changedValue(parameters); + return this; + } + + /** + * Adds a single element to genericParameters. + * + *

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

Example:

+ * + *
{@code
+   * builder.add2GenericParameters(GenericParameterDtoBuilder.create().build());
+   * }
+ * + * @param element the element to add + * @return current instance of builder + */ + public BuilderMethodDtoBuilder 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; + } + + /** + * Adds one element to genericParameters, configured through its builder. + * + * @param genericParameterBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public BuilderMethodDtoBuilder genericParameters( + Consumer genericParameterBuilderConsumer) { + GenericParameterDtoBuilder elementBuilder = new GenericParameterDtoBuilder(); + genericParameterBuilderConsumer.accept(elementBuilder); + return add2GenericParameters(elementBuilder.build()); + } + + /** + * Adds elements to genericParameters, each configured through its builder. + * + * @param genericParameterBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final BuilderMethodDtoBuilder genericParameters( + Consumer... genericParameterBuilderConsumers) { + for (Consumer consumer : genericParameterBuilderConsumers) { + genericParameters(consumer); + } + return this; + } + + /** + * Sets the value for genericParameters by invoking the provided supplier. + * + *

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

Example:

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

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

Example:

+ * + *
{@code
+   * builder.genericParameters(List.of(GenericParameterDtoBuilder.create().build()));
+   * }
+ * + * @param genericParameters genericParameters + * @return current instance of builder + */ + public BuilderMethodDtoBuilder genericParameters(List genericParameters) { + this.genericParameters = changedValue(genericParameters); + return this; + } + + /** + * Adds a single element to annotations. + * + *

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

Example:

+ * + *
{@code
+   * builder.add2Annotations(AnnotationDtoBuilder.create().build());
+   * }
+ * + * @param element the element to add + * @return current instance of builder + */ + public BuilderMethodDtoBuilder 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; + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param annotationType the annotation type (not null) + * @return current instance of builder + */ + public BuilderMethodDtoBuilder add2Annotations(Class annotationType) { + return add2Annotations(AnnotationDtoBuilder.create().annotationType(annotationType).build()); + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param packageName package of the annotation type + * @param className simple name of the annotation type + * @return current instance of builder + */ + public BuilderMethodDtoBuilder add2Annotations(String packageName, String className) { + return add2Annotations( + AnnotationDtoBuilder.create().annotationType(packageName, className).build()); + } + + /** + * Adds one element to annotations, configured through its builder. + * + * @param annotationBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public BuilderMethodDtoBuilder annotations( + Consumer annotationBuilderConsumer) { + AnnotationDtoBuilder elementBuilder = AnnotationDtoBuilder.create(); + annotationBuilderConsumer.accept(elementBuilder); + return add2Annotations(elementBuilder.build()); + } + + /** + * Adds elements to annotations, each configured through its builder. + * + * @param annotationBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final BuilderMethodDtoBuilder annotations( + Consumer... annotationBuilderConsumers) { + for (Consumer consumer : annotationBuilderConsumers) { + annotations(consumer); + } + return this; + } + + /** + * Sets the value for annotations by invoking the provided supplier. + * + *

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

Example:

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

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

Example:

+ * + *
{@code
+   * builder.annotations(List.of(AnnotationDtoBuilder.create().build()));
+   * }
+ * + * @param annotations annotations + * @return current instance of builder + */ + public BuilderMethodDtoBuilder annotations(List annotations) { + this.annotations = changedValue(annotations); + return this; + } + + /** + * Builds the configured DTO instance. + * + *

Example:

+ * + *
{@code
+   * BuilderMethodDto result = builder.build();
+   * }
+ */ + @Override + public BuilderMethodDto build() { + if (this.constructorField.isSet() && this.constructorField.value() == null) { + throw new IllegalStateException( + "Field 'constructorField' is marked as non-null but null value was provided"); + } + if (this.ordering.isSet() && this.ordering.value() == null) { + throw new IllegalStateException( + "Field 'ordering' is marked as non-null but null value was provided"); + } + if (this.priority.isSet() && this.priority.value() == null) { + throw new IllegalStateException( + "Field 'priority' is marked as non-null but null value was provided"); + } + if (this.isStatic.isSet() && this.isStatic.value() == null) { + throw new IllegalStateException( + "Field 'isStatic' is marked as non-null but null value was provided"); + } + BuilderMethodDto result = + new BuilderMethodDto(this.methodName.value(), this.returnType.value()); + this.code.ifSet(result::setCode); + this.constructorField.ifSet(result::setConstructorField); + this.exampleChainFragment.ifSet(result::setExampleChainFragment); + this.javadoc.ifSet(result::setJavadoc); + this.modifier.ifSet(result::setModifier); + this.ordering.ifSet(result::setOrdering); + this.priority.ifSet(result::setPriority); + this.sourceDescription.ifSet(result::setSourceDescription); + this.sourceFieldName.ifSet(result::setSourceFieldName); + this.isStatic.ifSet(result::setStatic); + this.parameters.ifSet(result::setParameters); + this.genericParameters.ifSet(result::setGenericParameters); + this.annotations.ifSet(result::setAnnotations); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("methodName", this.methodName) + .append("returnType", this.returnType) + .append("code", this.code) + .append("constructorField", this.constructorField) + .append("exampleChainFragment", this.exampleChainFragment) + .append("javadoc", this.javadoc) + .append("modifier", this.modifier) + .append("ordering", this.ordering) + .append("priority", this.priority) + .append("sourceDescription", this.sourceDescription) + .append("sourceFieldName", this.sourceFieldName) + .append("isStatic", this.isStatic) + .append("parameters", this.parameters) + .append("genericParameters", this.genericParameters) + .append("annotations", this.annotations) + .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 BuilderMethodDto with(Consumer b) { + BuilderMethodDtoBuilder builder; + try { + builder = new BuilderMethodDtoBuilder(BuilderMethodDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'BuilderMethodDtoBuilder.With' should only be implemented by classes, which could be casted to 'BuilderMethodDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default BuilderMethodDtoBuilder with() { + try { + return new BuilderMethodDtoBuilder(BuilderMethodDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'BuilderMethodDtoBuilder.With' should only be implemented by classes, which could be casted to 'BuilderMethodDto'", + ex); + } + } + } +} diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/type/BuilderNestedTypeDto.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/type/BuilderNestedTypeDto.java index baa9b56a..57b0b86e 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/type/BuilderNestedTypeDto.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/type/BuilderNestedTypeDto.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.LinkedList; import java.util.List; +import java.util.Objects; import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.model.annotation.AnnotationDto; import org.javahelpers.codegen.model.javadoc.JavadocDto; @@ -44,7 +45,7 @@ * *

For example, the "With" interface that allows DTOs to implement fluent modification methods. */ -public class BuilderNestedTypeDto { +public class BuilderNestedTypeDto implements BuilderNestedTypeDtoBuilder.With { /** The simple name of the nested type (e.g., "With"). */ private String typeName; @@ -96,6 +97,20 @@ public void addMethod(BuilderMethodDto method) { this.methods.add(method); } + /** + * Sets the methods of the nested type, replacing the current list. + * + * @param methods the methods to set + * @throws NullPointerException if methods is null + */ + public void setMethods(List methods) { + Objects.requireNonNull(methods); + if (methods != this.methods) { + this.methods.clear(); + this.methods.addAll(methods); + } + } + public JavadocDto getJavadoc() { return javadoc; } @@ -111,4 +126,18 @@ public List getAnnotations() { public void addAnnotation(AnnotationDto annotation) { this.annotations.add(annotation); } + + /** + * Sets the annotations of the nested type, replacing the current list. + * + * @param annotations the annotations to set + * @throws NullPointerException if annotations is null + */ + public void setAnnotations(List annotations) { + Objects.requireNonNull(annotations); + if (annotations != this.annotations) { + this.annotations.clear(); + this.annotations.addAll(annotations); + } + } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/type/BuilderNestedTypeDtoBuilder.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/type/BuilderNestedTypeDtoBuilder.java new file mode 100644 index 00000000..edb752f1 --- /dev/null +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/type/BuilderNestedTypeDtoBuilder.java @@ -0,0 +1,651 @@ +/* + * 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.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 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.NestedTypeDto; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; + +/** + * Builder for {@code org.javahelpers.simple.builders.processor.model.type.BuilderNestedTypeDto}. + * + *

This builder provides a fluent API for creating instances of + * org.javahelpers.simple.builders.processor.model.type.BuilderNestedTypeDto 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
+ * BuilderNestedTypeDto result = BuilderNestedTypeDtoBuilder.create()
+ *     .javadoc(new JavadocDto())
+ *     .javadoc(JavadocDto::new)
+ *     .javadoc(javadocDtoBuilder -> javadocDtoBuilder)
+ *     .typeName("example typeName")
+ *     .typeName("Hello %s", "World")
+ *     .typeName(() -> "example typeName")
+ *     .typeName(sb -> sb.append("text"))
+ *     .build();
+ * }
+ */ +public class BuilderNestedTypeDtoBuilder implements IBuilderBase { + + /** Tracked value for javadoc: javadoc. */ + private TrackedValue javadoc = unsetValue(); + + /** Tracked value for kind: kind. */ + private TrackedValue kind = unsetValue(); + + /** Tracked value for typeName: typeName. */ + private TrackedValue typeName = unsetValue(); + + /** Tracked value for visibility: visibility. */ + private TrackedValue visibility = unsetValue(); + + private TrackedValue> methods = unsetValue(); + private TrackedValue> annotations = unsetValue(); + + /** + * Empty constructor of builder for {@code + * org.javahelpers.simple.builders.processor.model.type.BuilderNestedTypeDto}. + */ + public BuilderNestedTypeDtoBuilder() {} + + /** + * Initialisation of builder for {@code + * org.javahelpers.simple.builders.processor.model.type.BuilderNestedTypeDto} by a instance. + * + * @param instance object instance for initialisiation + */ + public BuilderNestedTypeDtoBuilder(BuilderNestedTypeDto instance) { + this.javadoc = initialValue(instance.getJavadoc()); + this.kind = initialValue(instance.getKind()); + this.typeName = initialValue(instance.getTypeName()); + this.visibility = initialValue(instance.getVisibility()); + } + + /** + * Creating a new builder for {@code + * org.javahelpers.simple.builders.processor.model.type.BuilderNestedTypeDto}. + * + *

Example:

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

Generated from setter {@link BuilderNestedTypeDto#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 BuilderNestedTypeDtoBuilder 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 BuilderNestedTypeDto#setJavadoc(JavadocDto) + * setJavadoc(JavadocDto javadoc)} + * + *

Example:

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

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

Example:

+ * + *
{@code
+   * builder.javadoc(new JavadocDto());
+   * }
+ * + * @param javadoc javadoc + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder javadoc(JavadocDto javadoc) { + this.javadoc = changedValue(javadoc); + return this; + } + + /** + * Sets the value for kind by invoking the provided supplier. + * + *

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

Generated from setter {@link BuilderNestedTypeDto#setKind(NestedTypeDto.NestedTypeKind) + * setKind(NestedTypeDto.NestedTypeKind kind)} + * + * @param kind kind + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder kind(NestedTypeDto.NestedTypeKind kind) { + this.kind = changedValue(kind); + return this; + } + + /** + * Sets the value for typeName by executing the provided consumer. + * + *

Generated from setter {@link BuilderNestedTypeDto#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 BuilderNestedTypeDtoBuilder 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 BuilderNestedTypeDto#setTypeName(String) setTypeName(String + * typeName)} + * + *

Example:

+ * + *
{@code
+   * builder.typeName(() -> "example typeName");
+   * }
+ * + * @param typeNameSupplier supplier for typeName + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder 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 BuilderNestedTypeDto#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 BuilderNestedTypeDtoBuilder typeName(String format, Object... args) { + this.typeName = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for typeName. + * + *

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

Example:

+ * + *
{@code
+   * builder.typeName("example typeName");
+   * }
+ * + * @param typeName typeName + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder typeName(String typeName) { + this.typeName = changedValue(typeName); + return this; + } + + /** + * Sets the value for visibility by invoking the provided supplier. + * + *

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

Generated from setter {@link BuilderNestedTypeDto#setVisibility(AccessModifier) + * setVisibility(AccessModifier visibility)} + * + * @param visibility visibility + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder visibility(AccessModifier visibility) { + this.visibility = changedValue(visibility); + 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 BuilderNestedTypeDtoBuilder 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 BuilderNestedTypeDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Adds a single element to methods. + * + *

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

Example:

+ * + *
{@code
+   * builder.add2Methods(BuilderMethodDtoBuilder.create().build());
+   * }
+ * + * @param element the element to add + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder add2Methods(BuilderMethodDto 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; + } + + /** + * Adds one element to methods, configured through its builder. + * + * @param methodBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder methods( + Consumer methodBuilderConsumer) { + BuilderMethodDtoBuilder elementBuilder = BuilderMethodDtoBuilder.create(); + methodBuilderConsumer.accept(elementBuilder); + return add2Methods(elementBuilder.build()); + } + + /** + * Adds elements to methods, each configured through its builder. + * + * @param methodBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final BuilderNestedTypeDtoBuilder methods( + Consumer... methodBuilderConsumers) { + for (Consumer consumer : methodBuilderConsumers) { + methods(consumer); + } + return this; + } + + /** + * Sets the value for methods by invoking the provided supplier. + * + *

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

Example:

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

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

Example:

+ * + *
{@code
+   * builder.methods(List.of(BuilderMethodDtoBuilder.create().build()));
+   * }
+ * + * @param methods methods + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder methods(List methods) { + this.methods = changedValue(methods); + return this; + } + + /** + * Adds a single element to annotations. + * + *

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

Example:

+ * + *
{@code
+   * builder.add2Annotations(AnnotationDtoBuilder.create().build());
+   * }
+ * + * @param element the element to add + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder 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; + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param annotationType the annotation type (not null) + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder add2Annotations(Class annotationType) { + return add2Annotations(AnnotationDtoBuilder.create().annotationType(annotationType).build()); + } + + /** + * Adds one annotation of the given type to 2Annotations. + * + * @param packageName package of the annotation type + * @param className simple name of the annotation type + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder add2Annotations(String packageName, String className) { + return add2Annotations( + AnnotationDtoBuilder.create().annotationType(packageName, className).build()); + } + + /** + * Adds one element to annotations, configured through its builder. + * + * @param annotationBuilderConsumer consumer configuring the new element (not null) + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder annotations( + Consumer annotationBuilderConsumer) { + AnnotationDtoBuilder elementBuilder = AnnotationDtoBuilder.create(); + annotationBuilderConsumer.accept(elementBuilder); + return add2Annotations(elementBuilder.build()); + } + + /** + * Adds elements to annotations, each configured through its builder. + * + * @param annotationBuilderConsumers consumers configuring the new elements (not null) + * @return current instance of builder + */ + @SafeVarargs + public final BuilderNestedTypeDtoBuilder annotations( + Consumer... annotationBuilderConsumers) { + for (Consumer consumer : annotationBuilderConsumers) { + annotations(consumer); + } + return this; + } + + /** + * Sets the value for annotations by invoking the provided supplier. + * + *

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

Example:

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

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

Example:

+ * + *
{@code
+   * builder.annotations(List.of(AnnotationDtoBuilder.create().build()));
+   * }
+ * + * @param annotations annotations + * @return current instance of builder + */ + public BuilderNestedTypeDtoBuilder annotations(List annotations) { + this.annotations = changedValue(annotations); + return this; + } + + /** + * Builds the configured DTO instance. + * + *

Example:

+ * + *
{@code
+   * BuilderNestedTypeDto result = builder.build();
+   * }
+ */ + @Override + public BuilderNestedTypeDto build() { + BuilderNestedTypeDto result = new BuilderNestedTypeDto(); + this.javadoc.ifSet(result::setJavadoc); + this.kind.ifSet(result::setKind); + this.typeName.ifSet(result::setTypeName); + this.visibility.ifSet(result::setVisibility); + this.methods.ifSet(result::setMethods); + this.annotations.ifSet(result::setAnnotations); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("javadoc", this.javadoc) + .append("kind", this.kind) + .append("typeName", this.typeName) + .append("visibility", this.visibility) + .append("methods", this.methods) + .append("annotations", this.annotations) + .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 BuilderNestedTypeDto with(Consumer b) { + BuilderNestedTypeDtoBuilder builder; + try { + builder = new BuilderNestedTypeDtoBuilder(BuilderNestedTypeDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'BuilderNestedTypeDtoBuilder.With' should only be implemented by classes, which could be casted to 'BuilderNestedTypeDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default BuilderNestedTypeDtoBuilder with() { + try { + return new BuilderNestedTypeDtoBuilder(BuilderNestedTypeDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'BuilderNestedTypeDtoBuilder.With' should only be implemented by classes, which could be casted to 'BuilderNestedTypeDto'", + ex); + } + } + } +} diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java index 32ef0bc3..9fbe917e 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java @@ -51,9 +51,12 @@ import org.javahelpers.codegen.analysis.JavaLangMapper; 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.core.ClassFieldDto; +import org.javahelpers.codegen.model.core.ClassFieldDtoBuilder; import org.javahelpers.codegen.model.core.DeprecationInfoDto; 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.MethodParameterDto; import org.javahelpers.codegen.model.type.TypeName; @@ -65,7 +68,8 @@ import org.javahelpers.simple.builders.processor.generators.util.MethodGeneratorUtil; import org.javahelpers.simple.builders.processor.model.core.BuilderDefinitionDto; import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; -import org.javahelpers.simple.builders.processor.model.core.GetterInfoDto; +import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDtoBuilder; +import org.javahelpers.simple.builders.processor.model.core.GetterInfoDtoBuilder; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; /** Class for creating a specific BuilderDefinitionDto for an annotated DTO class. */ @@ -469,15 +473,13 @@ private static boolean isSkippedCopiedAnnotation(AnnotationDto annotation) { * @return the class field DTO */ private static ClassFieldDto convertToClassField(BuilderFieldDto field) { - ClassFieldDto classField = new ClassFieldDto(); - classField.setFieldName(field.getFieldNameInBuilder()); - - // Build the field type: TrackedValue - TypeName trackedValueType = - new TypeName("org.javahelpers.simple.builders.core.util", "TrackedValue"); - TypeName wrappedFieldType = - new TypeNameGeneric(trackedValueType, List.of(field.getFieldType())); - classField.setFieldType(wrappedFieldType); + ClassFieldDto classField = + ClassFieldDtoBuilder.create() + .fieldName(field.getFieldNameInBuilder()) + .fieldTypeGeneric( + new TypeName("org.javahelpers.simple.builders.core.util", "TrackedValue"), + field.getFieldType()) + .build(); classField.setVisibility(AccessModifier.PRIVATE); classField.setLiteralInitializer("unsetValue()"); @@ -949,24 +951,34 @@ private static Optional createFieldDto( TypeName fieldType = paramDto.getParameterType(); TypeMirror fieldTypeMirror = param.asType(); - BuilderFieldDto field = new BuilderFieldDto(); - field.setFieldNameInBuilder( - fieldNameInBuilder); // Use renamed field name for builder field storage - field.setOriginalFieldName(fieldName); // Framework annotations configure generation and are not copied onto generated code. fieldType.getAnnotations().removeIf(BuilderDefinitionCreator::isSkippedCopiedAnnotation); - field.setFieldType(fieldType); - // Store original javadoc description for reuse in builder method javadocs - field.setOriginalJavaDocDescription(StringUtils.trimToNull(javaDocDescription)); + // Extract annotations from the field parameter and exclude the framework's own + // annotations — they configure generation and are not copied onto generated code. + List annotations = FieldAnnotationExtractor.extractAnnotations(param, context); + annotations.removeIf(BuilderDefinitionCreator::isSkippedCopiedAnnotation); + + // Annotations could be assigned to Type or Parameter. + // To avoid duplication in generated code, we need to remove the duplications here. + annotations.removeAll(fieldType.getAnnotations()); - // Create javadoc for the tracked value field in the builder - String javaDocDescriptionOrFieldname = field.getJavaDocDescriptionOrFieldName(); - JavadocDto trackedValueJavadoc = - new JavadocDto( - "Tracked value for %s: %s.", - fieldNameInBuilder, javaDocDescriptionOrFieldname); - field.setJavaDoc(trackedValueJavadoc); + BuilderFieldDto field = + BuilderFieldDtoBuilder.create() + .fieldNameInBuilder(fieldNameInBuilder) + .originalFieldName(fieldName) + .fieldType(fieldType) + .originalJavaDocDescription(StringUtils.trimToNull(javaDocDescription)) + .parameterAnnotations(annotations) + .build(); + + // Create javadoc for the tracked value field in the builder (description derives from the + // just-built field, so it is applied after build) + field.setJavaDoc( + JavadocDtoBuilder.create() + .format("Tracked value for %s: %s.") + .args(fieldNameInBuilder, field.getJavaDocDescriptionOrFieldName()) + .build()); // Find matching getter on the DTO type using the builder field name TypeElement dtoTypeElement = context.getTypeElement(dtoType); @@ -977,20 +989,10 @@ private static Optional createFieldDto( getter.ifPresent( g -> field.setGetterInfo( - new GetterInfoDto( - g.getSimpleName().toString(), g.getAnnotation(Deprecated.class) != null))); - - // Extract annotations from the field parameter and exclude the framework's own - // annotations — they configure generation and are not copied onto generated code. - List annotations = FieldAnnotationExtractor.extractAnnotations(param, context); - annotations.removeIf(BuilderDefinitionCreator::isSkippedCopiedAnnotation); - - // Annotations could be assigned to Type or Parameter. - // To avoid duplication in generated code, we need to remove the duplications here. - annotations.removeAll(fieldType.getAnnotations()); - - // Store parameter annotations in field for generators to access - field.setParameterAnnotations(annotations); + GetterInfoDtoBuilder.create() + .getterName(g.getSimpleName().toString()) + .deprecated(g.getAnnotation(Deprecated.class) != null) + .build())); // Check if field has non-null constraint (annotation or primitive type) if (FieldAnnotationExtractor.hasNonNullConstraint(param) @@ -1402,10 +1404,10 @@ private static ExecutableElement findConstructorForBuilder( * @return the annotation DTO */ private static AnnotationDto createSuppressWarningsAnnotation() { - AnnotationDto annotation = new AnnotationDto(); - annotation.setAnnotationType(new TypeName("java.lang", "SuppressWarnings")); - annotation.addMember("value", "{\"deprecation\", \"removal\"}"); - return annotation; + return AnnotationDtoBuilder.create() + .annotationType("java.lang", "SuppressWarnings") + .members(m -> m.put("value", "{\"deprecation\", \"removal\"}")) + .build(); } /** diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/CustomizingDocumentationTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/CustomizingDocumentationTest.java index 83e8e77d..c25a65bd 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/CustomizingDocumentationTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/CustomizingDocumentationTest.java @@ -206,6 +206,7 @@ void testCustomGeneratorMethodCreation() { import org.javahelpers.simple.builders.processor.generators.MethodGenerator; import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; + import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; import org.javahelpers.codegen.model.method.MethodParameterDto; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; @@ -222,12 +223,14 @@ public List generateMethods(BuilderFieldDto field, TypeName bu String fieldName = field.getFieldNameInBuilder(); String methodName = "custom" + capitalize(fieldName); - BuilderMethodDto method = new BuilderMethodDto(methodName, builderType); - - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName("value"); - parameter.setParameterTypeName(new TypeName("java.lang", "String")); - method.addParameter(parameter); + BuilderMethodDto method = + BuilderMethodDtoBuilder.create() + .methodName(methodName) + .returnType(builderType) + .parameters( + el -> el.parameterName("value") + .parameterTypeName(new TypeName("java.lang", "String"))) + .build(); method.setCode("return this." + fieldName + "(value.toUpperCase());"); @@ -413,6 +416,7 @@ void testCompleteCustomValidationGenerator() { import org.javahelpers.simple.builders.processor.generators.MethodGenerator; import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; + import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; import org.javahelpers.codegen.model.method.MethodParameterDto; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; @@ -435,13 +439,15 @@ public List generateMethods(BuilderFieldDto field, TypeName bu String fieldName = field.getFieldNameInBuilder(); String methodName = "validated" + capitalize(fieldName); - BuilderMethodDto method = new BuilderMethodDto(methodName, builderType); - String parameterName = fieldName; - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName(parameterName); - parameter.setParameterTypeName(new TypeName("java.lang", "String")); - method.addParameter(parameter); + BuilderMethodDto method = + BuilderMethodDtoBuilder.create() + .methodName(methodName) + .returnType(builderType) + .parameters( + el -> el.parameterName(parameterName) + .parameterTypeName(new TypeName("java.lang", "String"))) + .build(); method.setCode(String.format( "if (%s != null && %s.contains(\\"@\\")) { " + @@ -487,8 +493,10 @@ void testCompleteCustomValidationEnhancer() { import org.javahelpers.simple.builders.processor.generators.BuilderEnhancer; import org.javahelpers.codegen.model.annotation.AnnotationDto; + import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; import org.javahelpers.simple.builders.processor.model.core.BuilderDefinitionDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; + import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; @@ -514,8 +522,10 @@ public void enhanceBuilder(BuilderDefinitionDto builderDto, BuilderProcessingCon // Add @Valid annotation if available if (isValidationAvailable(context)) { - AnnotationDto validAnnotation = new AnnotationDto(); - validAnnotation.setAnnotationType(new TypeName("javax.validation", "Valid")); + AnnotationDto validAnnotation = + AnnotationDtoBuilder.create() + .annotationType(new TypeName("javax.validation", "Valid")) + .build(); builderDto.addClassAnnotation(validAnnotation); } @@ -530,8 +540,12 @@ public int getPriority() { private BuilderMethodDto createValidateMethod() { TypeName returnType = new TypeName("java.lang", "Void"); - BuilderMethodDto method = new BuilderMethodDto("validate", returnType); - method.setCode("// Validation logic here"); + BuilderMethodDto method = + BuilderMethodDtoBuilder.create() + .methodName("validate") + .returnType(returnType) + .code("// Validation logic here") + .build(); return method; } @@ -598,6 +612,7 @@ void testDateParserGeneratorExample() { import org.javahelpers.simple.builders.processor.generators.MethodGenerator; import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; + import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; import org.javahelpers.codegen.model.method.MethodParameterDto; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; @@ -616,13 +631,15 @@ public List generateMethods(BuilderFieldDto field, TypeName bu String fieldName = field.getFieldNameInBuilder(); String methodName = fieldName + "FromString"; - BuilderMethodDto method = new BuilderMethodDto(methodName, builderType); - String parameterName = fieldName + "String"; - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName(parameterName); - parameter.setParameterTypeName(new TypeName("java.lang", "String")); - method.addParameter(parameter); + BuilderMethodDto method = + BuilderMethodDtoBuilder.create() + .methodName(methodName) + .returnType(builderType) + .parameters( + el -> el.parameterName(parameterName) + .parameterTypeName(new TypeName("java.lang", "String"))) + .build(); method.setCode(String.format( "try { return this.%s(java.time.LocalDate.parse(%s)); } " + @@ -662,6 +679,7 @@ void testBuilderFactoryEnhancerExample() { import org.javahelpers.simple.builders.processor.generators.BuilderEnhancer; import org.javahelpers.simple.builders.processor.model.core.BuilderDefinitionDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; + import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; import org.javahelpers.codegen.model.method.MethodParameterDto; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; @@ -678,13 +696,15 @@ public void enhanceBuilder(BuilderDefinitionDto builderDto, BuilderProcessingCon TypeName builderType = builderDto.getBuilderTypeName(); // Add static factory method (conceptual - actual API may differ) - BuilderMethodDto factoryMethod = new BuilderMethodDto("from", builderType); - factoryMethod.setStatic(true); - - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName("template"); - parameter.setParameterTypeName(builderType); - factoryMethod.addParameter(parameter); + BuilderMethodDto factoryMethod = + BuilderMethodDtoBuilder.create() + .methodName("from") + .returnType(builderType) + .isStatic(true) + .parameters( + el -> el.parameterName("template") + .parameterTypeName(builderType)) + .build(); factoryMethod.setCode(String.format("return new %s();", builderType.getClassName())); diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/ProcessorDtoBuildersTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/ProcessorDtoBuildersTest.java new file mode 100644 index 00000000..22032408 --- /dev/null +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/ProcessorDtoBuildersTest.java @@ -0,0 +1,206 @@ +/* + * 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 static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +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.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.TypeName; +import org.javahelpers.codegen.model.type.TypeNameList; +import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; +import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDtoBuilder; +import org.javahelpers.simple.builders.processor.model.core.GetterInfoDto; +import org.javahelpers.simple.builders.processor.model.core.GetterInfoDtoBuilder; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; +import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDtoBuilder; +import org.javahelpers.simple.builders.processor.model.type.BuilderNestedTypeDto; +import org.javahelpers.simple.builders.processor.model.type.BuilderNestedTypeDtoBuilder; +import org.junit.jupiter.api.Test; + +/** Covers the committed builders of the processor-internal DTOs. */ +class ProcessorDtoBuildersTest { + + @Test + void builderFieldDtoBuilderCoversAllProperties() { + BuilderFieldDto dto = + BuilderFieldDtoBuilder.create() + .originalFieldName("persons") + .fieldNameInBuilder("persons") + .setterName("setPersons") + .fieldType(String.class) + .nonNullable(true) + .fieldGenerics(g -> g.name("T")) + .parameterAnnotations(a -> a.annotationType("java.lang", "Deprecated")) + .defaultValue("\"none\"") + .build(); + + assertEquals("persons", dto.getOriginalFieldName()); + assertEquals("persons", dto.getFieldNameInBuilder()); + assertEquals("setPersons", dto.getSetterName().orElseThrow()); + assertEquals(TypeName.of(String.class), dto.getFieldType()); + assertTrue(dto.isNonNullable()); + assertEquals("T", dto.getFieldGenerics().get(0).getName()); + assertEquals( + new TypeName("java.lang", "Deprecated"), + dto.getParameterAnnotations().get(0).getAnnotationType()); + assertEquals("\"none\"", dto.getDefaultValue().orElseThrow()); + + BuilderFieldDto copy = dto.with(b -> b.originalFieldName("renamed")); + assertEquals("renamed", copy.getOriginalFieldName()); + assertEquals("persons", dto.getOriginalFieldName()); + } + + @Test + void getterInfoDtoBuilderBuildsRecord() { + GetterInfoDto dto = + GetterInfoDtoBuilder.create().getterName("getPersons").deprecated(false).build(); + + assertEquals("getPersons", dto.getGetterName()); + assertFalse(dto.deprecated()); + + GetterInfoDto copy = dto.with(b -> b.deprecated(true)); + assertTrue(copy.deprecated()); + assertFalse(dto.deprecated()); + } + + @Test + void builderMethodDtoBuilderCoversAllProperties() { + BuilderMethodDto dto = + BuilderMethodDtoBuilder.create() + .methodName("persons") + .returnTypeList(String.class) + .code("return $builder:N.$fieldName:N;") + .priority(42) + .ordering(7) + .isStatic(true) + .modifier(AccessModifier.PRIVATE) + .sourceFieldName("persons") + .parameters(el -> el.parameterName("value").parameterTypeName("java.lang", "String")) + .build(); + + assertEquals("persons", dto.getMethodName()); + assertEquals(TypeNameList.of(String.class), dto.getReturnType()); + assertTrue(dto.hasCode()); + assertEquals(42, dto.getPriority()); + assertEquals(7, dto.getOrdering()); + assertTrue(dto.isStatic()); + assertEquals(AccessModifier.PRIVATE, dto.getModifier().orElseThrow()); + assertEquals("persons", dto.getSourceFieldName()); + assertEquals(1, dto.getParameters().size()); + + BuilderMethodDto copy = dto.with(b -> b.methodName("renamed")); + assertEquals("renamed", copy.getMethodName()); + assertEquals("persons", dto.getMethodName()); + } + + @Test + void builderNestedTypeDtoBuilderCoversAllProperties() { + BuilderNestedTypeDto dto = + BuilderNestedTypeDtoBuilder.create() + .typeName("Factory") + .kind(NestedTypeDto.NestedTypeKind.CLASS) + .visibility(AccessModifier.PROTECTED) + .methods(el -> el.methodName("create")) + .build(); + + assertEquals("Factory", dto.getTypeName()); + assertEquals(NestedTypeDto.NestedTypeKind.CLASS, dto.getKind()); + assertEquals(AccessModifier.PROTECTED, dto.getVisibility()); + assertEquals("create", dto.getMethods().get(0).getMethodName()); + + BuilderNestedTypeDto copy = dto.with(b -> b.typeName("Renamed")); + assertEquals("Renamed", copy.getTypeName()); + assertEquals("Factory", dto.getTypeName()); + } + + @Test + void builderMethodDtoBuilderCollectionSuite() { + MethodParameterDto param = + MethodParameterDtoBuilder.create() + .parameterName("value") + .parameterTypeName("java.lang", "String") + .build(); + AnnotationDto anno = + AnnotationDtoBuilder.create().annotationType("java.lang", "Deprecated").build(); + GenericParameterDto generic = + GenericParameterDtoBuilder.create().name("T").add2UpperBounds(String.class).build(); + + BuilderMethodDto dto = + BuilderMethodDtoBuilder.create() + .methodName("m") + .parameters(List.of(param)) + .parameters(() -> List.of(param)) + .parameters(el -> el.parameterName("x")) + .add2Parameters(param) + .add2Annotations(anno) + .add2GenericParameters(generic) + .build(); + + assertEquals(3, dto.getParameters().size()); + assertEquals(1, dto.getAnnotations().size()); + assertEquals(1, dto.getGenericParameters().size()); + + BuilderMethodDtoBuilder.create() + .methodName("m") + .returnType("java.lang", "Void") + .returnTypeList(String.class); + } + + @Test + void builderFieldDtoBuilderMethodsAndTypeNameOverloads() { + BuilderFieldDto dto = + BuilderFieldDtoBuilder.create() + .fieldType("java.lang", "String") + .fieldTypeList(String.class) + .methods(el -> el.methodName("setter")) + .add2Methods(BuilderMethodDtoBuilder.create().methodName("other").build()) + .build(); + + assertEquals(2, dto.getMethods().size()); + assertEquals(TypeNameList.of(String.class), dto.getFieldType()); + } + + @Test + void builderNestedTypeDtoBuilderAnnotations() { + BuilderNestedTypeDto dto = + BuilderNestedTypeDtoBuilder.create() + .typeName("Inner") + .annotations(el -> el.annotationType("java.lang", "Deprecated")) + .add2Annotations( + AnnotationDtoBuilder.create().annotationType("java.lang", "Deprecated").build()) + .build(); + + assertEquals(2, dto.getAnnotations().size()); + } +} diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/generators/builder/CoreMethodsEnhancerTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/generators/builder/CoreMethodsEnhancerTest.java index 46789254..7e3001af 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/generators/builder/CoreMethodsEnhancerTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/generators/builder/CoreMethodsEnhancerTest.java @@ -31,6 +31,7 @@ import org.javahelpers.simple.builders.processor.model.core.BuilderConfiguration; import org.javahelpers.simple.builders.processor.model.core.BuilderDefinitionDto; import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; +import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDtoBuilder; import org.junit.jupiter.api.Test; class CoreMethodsEnhancerTest { @@ -100,10 +101,10 @@ private static BuilderDefinitionDto builder() { } private static BuilderFieldDto field() { - BuilderFieldDto field = new BuilderFieldDto(); - field.setOriginalFieldName("isStatic"); - field.setFieldNameInBuilder("isStatic"); - field.setFieldType(TypeName.of(Boolean.class)); - return field; + return BuilderFieldDtoBuilder.create() + .originalFieldName("isStatic") + .fieldNameInBuilder("isStatic") + .fieldType(Boolean.class) + .build(); } } diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreatorTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreatorTest.java index b24aa64a..feb86570 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreatorTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreatorTest.java @@ -29,10 +29,10 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; -import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.testing.CodegenTestUtils; import org.javahelpers.codegen.testing.ProbeProcessor; import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; +import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDtoBuilder; import org.junit.jupiter.api.Test; class BuilderDefinitionCreatorTest { @@ -133,9 +133,9 @@ void setterSourceDescriptionAllowsUnknownDto() { } private static BuilderFieldDto field() { - BuilderFieldDto field = new BuilderFieldDto(); - field.setOriginalFieldName("isStatic"); - field.setFieldType(TypeName.of(Boolean.class)); - return field; + return BuilderFieldDtoBuilder.create() + .originalFieldName("isStatic") + .fieldType(Boolean.class) + .build(); } } diff --git a/simple-processor/src/main/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractor.java b/simple-processor/src/main/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractor.java index b77fb1d2..6f177006 100644 --- a/simple-processor/src/main/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractor.java +++ b/simple-processor/src/main/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractor.java @@ -25,6 +25,7 @@ package org.javahelpers.codegen.analysis; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -38,6 +39,7 @@ import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNamePrimitive; @@ -134,24 +136,27 @@ private static Optional extractAnnotation( return Optional.empty(); } - // Create AnnotationDto - AnnotationDto annotationDto = new AnnotationDto(); - // Extract package and class name String packageName = context.getPackageName(annotationType); String simpleName = annotationType.getSimpleName().toString(); - annotationDto.setAnnotationType(new TypeName(packageName, simpleName)); // Extract annotation members (parameters) Map elementValues = mirror.getElementValues(); + Map members = new LinkedHashMap<>(); for (Map.Entry entry : elementValues.entrySet()) { String memberName = entry.getKey().getSimpleName().toString(); String memberValue = formatAnnotationValue(entry.getValue()); - annotationDto.addMember(memberName, memberValue); + members.put(memberName, memberValue); } + AnnotationDto annotationDto = + AnnotationDtoBuilder.create() + .annotationType(new TypeName(packageName, simpleName)) + .members(members) + .build(); + context.debug(" -> Added annotation: %s", annotationType.getQualifiedName()); return Optional.of(annotationDto); } diff --git a/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangMapper.java b/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangMapper.java index ffda81da..a2fa942e 100644 --- a/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangMapper.java +++ b/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangMapper.java @@ -43,7 +43,9 @@ import org.apache.commons.lang3.Strings; import org.javahelpers.codegen.model.annotation.AnnotationDto; 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.TypeName; import org.javahelpers.codegen.model.type.TypeNameArray; import org.javahelpers.codegen.model.type.TypeNameGeneric; @@ -95,13 +97,15 @@ public static List map2GenericParameterDtos( */ public static GenericParameterDto map2GenericParameterDto( TypeParameterElement tp, TypeMappingContext context) { - GenericParameterDto g = new GenericParameterDto(); - g.setName(tp.getSimpleName().toString()); - tp.getBounds().stream() - .filter(b -> !"java.lang.Object".equals(b.toString())) - .map(b -> extractType(b, context)) - .forEach(g::addUpperBound); - return g; + List upperBounds = + tp.getBounds().stream() + .filter(b -> !"java.lang.Object".equals(b.toString())) + .map(b -> extractType(b, context)) + .toList(); + return GenericParameterDtoBuilder.create() + .name(tp.getSimpleName().toString()) + .upperBounds(upperBounds) + .build(); } /** @@ -113,8 +117,6 @@ public static GenericParameterDto map2GenericParameterDto( */ public static MethodParameterDto map2MethodParameter( VariableElement param, TypeMappingContext context) { - MethodParameterDto result = new MethodParameterDto(); - result.setParameterName(param.getSimpleName().toString()); TypeMirror typeMirror = param.asType(); TypeName typeName = extractType(typeMirror, context); if (typeName == null) { @@ -123,8 +125,10 @@ public static MethodParameterDto map2MethodParameter( setEmptyConstructorInfo(typeName, param, context); - result.setParameterTypeName(typeName); - return result; + return MethodParameterDtoBuilder.create() + .parameterName(param.getSimpleName().toString()) + .parameterTypeName(typeName) + .build(); } /** diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java index a2345289..ef7be6da 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java @@ -54,8 +54,11 @@ import org.javahelpers.codegen.enums.FormattingMode; import org.javahelpers.codegen.logging.ProcessingLogger; import org.javahelpers.codegen.model.core.ClassFieldDto; +import org.javahelpers.codegen.model.core.ClassFieldDtoBuilder; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.testing.CodegenTestUtils; import org.junit.jupiter.api.Test; @@ -147,36 +150,48 @@ protected GenerationTargetClassDto mapToTargetSpecification( MinimalTargetDefinition definition, CodegenConfiguration configuration, AnnotationProcessingContext ctx) { - GenerationTargetClassDto target = new GenerationTargetClassDto(); - target.setTypeName(definition.builderTypeName()); - target.setClassAccessModifier(AccessModifier.PUBLIC); - target.setFormattingMode(FormattingMode.NONE); - - ClassFieldDto field = new ClassFieldDto(); - field.setFieldName("target"); - field.setFieldType(definition.sourceTypeName()); - field.setVisibility(AccessModifier.PRIVATE); - field.setLiteralInitializer("new " + definition.sourceTypeName().getClassName() + "()"); + GenerationTargetClassDto target = + GenerationTargetClassDtoBuilder.create() + .typeName(definition.builderTypeName()) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); + + ClassFieldDto field = + ClassFieldDtoBuilder.create() + .fieldName("target") + .fieldType(definition.sourceTypeName()) + .visibility(AccessModifier.PRIVATE) + .literalInitializer("new " + definition.sourceTypeName().getClassName() + "()") + .build(); target.addClassField(field); for (ExecutableElement setter : definition.setters()) { String setterName = setter.getSimpleName().toString(); String methodName = StringUtils.uncapitalize(Strings.CI.removeStart(setterName, "set")); - MethodDto method = new MethodDto(methodName, definition.builderTypeName()); - method.setModifier(AccessModifier.PUBLIC); + MethodDto method = + MethodDtoBuilder.create() + .methodName(methodName) + .returnType(definition.builderTypeName()) + .modifier(AccessModifier.PUBLIC) + .code( + """ + target.$setterName:N($paramName:N); + return this;""") + .build(); String paramName = setter.getParameters().get(0).getSimpleName().toString(); method.addParameter(JavaLangMapper.map2MethodParameter(setter.getParameters().get(0), ctx)); - method.setCode( - """ - target.$setterName:N($paramName:N); - return this;"""); method.addArgument("setterName", setterName); method.addArgument("paramName", paramName); target.addMethod(method); } - MethodDto build = new MethodDto("build", definition.sourceTypeName()); - build.setModifier(AccessModifier.PUBLIC); - build.setCode("return target;"); + MethodDto build = + MethodDtoBuilder.create() + .methodName("build") + .returnType(definition.sourceTypeName()) + .modifier(AccessModifier.PUBLIC) + .code("return target;") + .build(); target.addMethod(build); return target; }