Compare commits
26 Commits
record-bui
...
record-bui
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
abfc12bdb0 | ||
|
|
6c0fac0dff | ||
|
|
ae527cd8e5 | ||
|
|
73ba62057a | ||
|
|
87998aba68 | ||
|
|
04a0904d3f | ||
|
|
aa072af8e1 | ||
|
|
b435b5d3fd | ||
|
|
d3c1bb36f3 | ||
|
|
c3719326c9 | ||
|
|
661d0818c0 | ||
|
|
79bc8396f2 | ||
|
|
b2149622e4 | ||
|
|
0718e37f76 | ||
|
|
d112a1b352 | ||
|
|
86093b6bad | ||
|
|
7b6ad4d7ba | ||
|
|
cd059f1207 | ||
|
|
642dd01421 | ||
|
|
efd1a6b0d4 | ||
|
|
b525eddc76 | ||
|
|
d3828eda74 | ||
|
|
fef69af183 | ||
|
|
99f9639b82 | ||
|
|
43bc65e258 | ||
|
|
bae1b771b7 |
264
README.md
264
README.md
@@ -89,168 +89,176 @@ _Hat tip to [Benji Weber](https://benjiweber.co.uk/blog/2020/09/19/fun-with-java
|
||||
|
||||
## Builder Class Definition
|
||||
|
||||
(Note: you can see a builder class built using `@RecordBuilderFull` here: [SingleItemsBuilder.java](https://gist.github.com/Randgalt/8aa487a847ea2acdd76d702f7cf17d6a))
|
||||
(Note: you can see a builder class built using `@RecordBuilderFull` here: [FullRecordBuilder.java](https://gist.github.com/Randgalt/8aa487a847ea2acdd76d702f7cf17d6a))
|
||||
|
||||
The full builder class is defined as:
|
||||
|
||||
```java
|
||||
public class NameAndAgeBuilder {
|
||||
private String name;
|
||||
private String name;
|
||||
|
||||
private int age;
|
||||
private int age;
|
||||
|
||||
private NameAndAgeBuilder() {
|
||||
}
|
||||
private NameAndAgeBuilder() {
|
||||
}
|
||||
|
||||
private NameAndAgeBuilder(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
private NameAndAgeBuilder(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
/**
|
||||
* Static constructor/builder. Can be used instead of new NameAndAge(...)
|
||||
*/
|
||||
public static NameAndAge NameAndAge(String name, int age) {
|
||||
return new NameAndAge(name, age);
|
||||
}
|
||||
/**
|
||||
* Static constructor/builder. Can be used instead of new NameAndAge(...)
|
||||
*/
|
||||
public static NameAndAge NameAndAge(String name, int age) {
|
||||
return new NameAndAge(name, age);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new builder with all fields set to default Java values
|
||||
*/
|
||||
public static NameAndAgeBuilder builder() {
|
||||
return new NameAndAgeBuilder();
|
||||
}
|
||||
/**
|
||||
* Return a new builder with all fields set to default Java values
|
||||
*/
|
||||
public static NameAndAgeBuilder builder() {
|
||||
return new NameAndAgeBuilder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new builder with all fields set to the values taken from the given record instance
|
||||
*/
|
||||
public static NameAndAgeBuilder builder(NameAndAge from) {
|
||||
return new NameAndAgeBuilder(from.name(), from.age());
|
||||
}
|
||||
/**
|
||||
* Return a new builder with all fields set to the values taken from the given record instance
|
||||
*/
|
||||
public static NameAndAgeBuilder builder(NameAndAge from) {
|
||||
return new NameAndAgeBuilder(from.name(), from.age());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a "with"er for an existing record instance
|
||||
*/
|
||||
public static NameAndAgeBuilder.With from(NameAndAge from) {
|
||||
return new NameAndAgeBuilder.With() {
|
||||
@Override
|
||||
public String name() {
|
||||
return from.name();
|
||||
}
|
||||
/**
|
||||
* Return a "with"er for an existing record instance
|
||||
*/
|
||||
public static NameAndAgeBuilder.With from(NameAndAge from) {
|
||||
return new _FromWith(from);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int age() {
|
||||
return from.age();
|
||||
}
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Return a stream of the record components as map entries keyed with the component name and the value as the component value
|
||||
*/
|
||||
public static Stream<Map.Entry<String, Object>> stream(NameAndAge record) {
|
||||
return Stream.of(new AbstractMap.SimpleImmutableEntry<>("name", record.name()),
|
||||
new AbstractMap.SimpleImmutableEntry<>("age", record.age()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a stream of the record components as map entries keyed with the component name and the value as the component value
|
||||
*/
|
||||
public static Stream<Map.Entry<String, Object>> stream(NameAndAge record) {
|
||||
return Stream.of(Map.entry("name", record.name()),
|
||||
Map.entry("age", record.age()));
|
||||
}
|
||||
/**
|
||||
* Return a new record instance with all fields set to the current values in this builder
|
||||
*/
|
||||
public NameAndAge build() {
|
||||
return new NameAndAge(name, age);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new record instance with all fields set to the current values in this builder
|
||||
*/
|
||||
public NameAndAge build() {
|
||||
return new NameAndAge(name, age);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "NameAndAgeBuilder[name=" + name + ", age=" + age + "]";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "NameAndAgeBuilder[name=" + name + ", age=" + age + "]";
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(name, age);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(name, age);
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return (this == o) || ((o instanceof NameAndAgeBuilder r)
|
||||
&& Objects.equals(name, r.name)
|
||||
&& (age == r.age));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return (this == o) || ((o instanceof NameAndAgeBuilder r)
|
||||
&& Objects.equals(name, r.name)
|
||||
&& (age == r.age));
|
||||
}
|
||||
/**
|
||||
* Set a new value for the {@code name} record component in the builder
|
||||
*/
|
||||
public NameAndAgeBuilder name(String name) {
|
||||
this.name = name;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a new value for the {@code name} record component in the builder
|
||||
*/
|
||||
public NameAndAgeBuilder name(String name) {
|
||||
this.name = name;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current value for the {@code name} record component in the builder
|
||||
*/
|
||||
public String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a new value for the {@code age} record component in the builder
|
||||
*/
|
||||
public NameAndAgeBuilder age(int age) {
|
||||
this.age = age;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current value for the {@code age} record component in the builder
|
||||
*/
|
||||
public int age() {
|
||||
return age;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add withers to {@code NameAndAge}
|
||||
*/
|
||||
public interface With {
|
||||
/**
|
||||
* Return the current value for the {@code name} record component in the builder
|
||||
*/
|
||||
String name();
|
||||
public String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a new value for the {@code age} record component in the builder
|
||||
*/
|
||||
public NameAndAgeBuilder age(int age) {
|
||||
this.age = age;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current value for the {@code age} record component in the builder
|
||||
*/
|
||||
int age();
|
||||
|
||||
/**
|
||||
* Return a new record builder using the current values
|
||||
*/
|
||||
default NameAndAgeBuilder with() {
|
||||
return new NameAndAgeBuilder(name(), age());
|
||||
public int age() {
|
||||
return age;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new record built from the builder passed to the given consumer
|
||||
* Add withers to {@code NameAndAge}
|
||||
*/
|
||||
default NameAndAge with(Consumer<NameAndAgeBuilder> consumer) {
|
||||
NameAndAgeBuilder builder = with();
|
||||
consumer.accept(builder);
|
||||
return builder.build();
|
||||
public interface With {
|
||||
/**
|
||||
* Return the current value for the {@code name} record component in the builder
|
||||
*/
|
||||
String name();
|
||||
|
||||
/**
|
||||
* Return the current value for the {@code age} record component in the builder
|
||||
*/
|
||||
int age();
|
||||
|
||||
/**
|
||||
* Return a new record builder using the current values
|
||||
*/
|
||||
default NameAndAgeBuilder with() {
|
||||
return new NameAndAgeBuilder(name(), age());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new record built from the builder passed to the given consumer
|
||||
*/
|
||||
default NameAndAge with(Consumer<NameAndAgeBuilder> consumer) {
|
||||
NameAndAgeBuilder builder = with();
|
||||
consumer.accept(builder);
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new instance of {@code NameAndAge} with a new value for {@code name}
|
||||
*/
|
||||
default NameAndAge withName(String name) {
|
||||
return new NameAndAge(name, age());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new instance of {@code NameAndAge} with a new value for {@code age}
|
||||
*/
|
||||
default NameAndAge withAge(int age) {
|
||||
return new NameAndAge(name(), age);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new instance of {@code NameAndAge} with a new value for {@code name}
|
||||
*/
|
||||
default NameAndAge withName(String name) {
|
||||
return new NameAndAge(name, age());
|
||||
}
|
||||
private static final class _FromWith implements NameAndAgeBuilder.With {
|
||||
private final NameAndAge from;
|
||||
|
||||
/**
|
||||
* Return a new instance of {@code NameAndAge} with a new value for {@code age}
|
||||
*/
|
||||
default NameAndAge withAge(int age) {
|
||||
return new NameAndAge(name(), age);
|
||||
private _FromWith(NameAndAge from) {
|
||||
this.from = from;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return from.name();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int age() {
|
||||
return from.age();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
24
pom.xml
24
pom.xml
@@ -5,7 +5,7 @@
|
||||
<groupId>io.soabase.record-builder</groupId>
|
||||
<artifactId>record-builder</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<version>31</version>
|
||||
<version>34</version>
|
||||
|
||||
<modules>
|
||||
<module>record-builder-core</module>
|
||||
@@ -32,6 +32,9 @@
|
||||
<maven-shade-plugin-version>3.2.1</maven-shade-plugin-version>
|
||||
<maven-release-plugin-version>2.5.3</maven-release-plugin-version>
|
||||
<maven-jar-plugin-version>3.2.0</maven-jar-plugin-version>
|
||||
<maven-surefire-plugin-version>3.0.0-M5</maven-surefire-plugin-version>
|
||||
|
||||
<jacoco-maven-plugin-version>0.8.7</jacoco-maven-plugin-version>
|
||||
|
||||
<license-file-path>src/etc/header.txt</license-file-path>
|
||||
|
||||
@@ -77,7 +80,7 @@
|
||||
<url>https://github.com/randgalt/record-builder</url>
|
||||
<connection>scm:git:https://github.com/randgalt/record-builder.git</connection>
|
||||
<developerConnection>scm:git:git@github.com:randgalt/record-builder.git</developerConnection>
|
||||
<tag>record-builder-31</tag>
|
||||
<tag>record-builder-34</tag>
|
||||
</scm>
|
||||
|
||||
<issueManagement>
|
||||
@@ -153,6 +156,12 @@
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin-version}</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
@@ -319,6 +328,12 @@
|
||||
<artifactId>maven-gpg-plugin</artifactId>
|
||||
<version>${maven-gpg-plugin-version}</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<version>${jacoco-maven-plugin-version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
|
||||
@@ -352,6 +367,11 @@
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-release-plugin</artifactId>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<parent>
|
||||
<groupId>io.soabase.record-builder</groupId>
|
||||
<artifactId>record-builder</artifactId>
|
||||
<version>31</version>
|
||||
<version>34</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
||||
@@ -99,6 +99,11 @@ public @interface RecordBuilder {
|
||||
*/
|
||||
String componentsMethodName() default "stream";
|
||||
|
||||
/**
|
||||
* If true, a "With" interface is generated and an associated static factory
|
||||
*/
|
||||
boolean enableWither() default true;
|
||||
|
||||
/**
|
||||
* The name to use for the nested With class
|
||||
*/
|
||||
@@ -139,6 +144,11 @@ public @interface RecordBuilder {
|
||||
*/
|
||||
boolean emptyDefaultForOptional() default true;
|
||||
|
||||
/**
|
||||
* Add non-optional setter methods for optional record components.
|
||||
*/
|
||||
boolean addConcreteSettersForOptional() default false;
|
||||
|
||||
/**
|
||||
* Add not-null checks for record components annotated with any annotation named either "NotNull",
|
||||
* "NoNull", or "NonNull" (see {@link #interpretNotNullsPattern()} for the actual regex matching pattern).
|
||||
@@ -187,6 +197,79 @@ public @interface RecordBuilder {
|
||||
* When enabled, adds functional methods to the nested "With" class (such as {@code map()} and {@code accept()}).
|
||||
*/
|
||||
boolean addFunctionalMethodsToWith() default false;
|
||||
|
||||
/**
|
||||
* If set, all builder setter methods will be prefixed with this string. Camel-casing will
|
||||
* still be enforced, so if this option is set to "set" a field named "myField" will get
|
||||
* a corresponding setter named "setMyField".
|
||||
*/
|
||||
String setterPrefix() default "";
|
||||
|
||||
/**
|
||||
* If true, getters will be generated for the Builder class.
|
||||
*/
|
||||
boolean enableGetters() default true;
|
||||
|
||||
/**
|
||||
* If set, all builder getter methods will be prefixed with this string. Camel-casing will
|
||||
* still be enforced, so if this option is set to "get", a field named "myField" will get
|
||||
* a corresponding getter named "getMyField".
|
||||
*/
|
||||
String getterPrefix() default "";
|
||||
|
||||
/**
|
||||
* If set, all boolean builder getter methods will be prefixed with this string.
|
||||
* Camel-casing will still be enforced, so if this option is set to "is", a field named
|
||||
* "myField" will get a corresponding getter named "isMyField".
|
||||
*/
|
||||
String booleanPrefix() default "";
|
||||
|
||||
/**
|
||||
* If set, the Builder will contain an internal interface with this name. This interface
|
||||
* contains getters for all the fields in the Record prefixed with the value supplied in
|
||||
* {@link this.getterPrefix} and {@link this.booleanPrefix}. This interface can be
|
||||
* implemented by the original Record to have proper bean-style prefixed getters.
|
||||
*
|
||||
* Please note that unless either of the aforementioned prefixes are set,
|
||||
* this option does nothing.
|
||||
*/
|
||||
String beanClassName() default "";
|
||||
|
||||
/**
|
||||
* If true, generated classes are annotated with {@code RecordBuilderGenerated} which has a retention
|
||||
* policy of {@code CLASS}. This ensures that analyzers such as Jacoco will ignore the generated class.
|
||||
*/
|
||||
boolean addClassRetainedGenerated() default false;
|
||||
|
||||
/**
|
||||
* The {@link #fromMethodName} method instantiates an internal private class. This is the
|
||||
* name of that class.
|
||||
*/
|
||||
String fromWithClassName() default "_FromWith";
|
||||
|
||||
/**
|
||||
* If true, a functional-style builder is added so that record instances can be instantiated
|
||||
* without {@code new}.
|
||||
*/
|
||||
boolean addStaticBuilder() default true;
|
||||
|
||||
/**
|
||||
* If {@link #addSingleItemCollectionBuilders()} and {@link #useImmutableCollections()} are enabled the builder
|
||||
* uses an internal class to track changes to lists. This is the name of that class.
|
||||
*/
|
||||
String mutableListClassName() default "_MutableList";
|
||||
|
||||
/**
|
||||
* If {@link #addSingleItemCollectionBuilders()} and {@link #useImmutableCollections()} are enabled the builder
|
||||
* uses an internal class to track changes to sets. This is the name of that class.
|
||||
*/
|
||||
String mutableSetClassName() default "_MutableSet";
|
||||
|
||||
/**
|
||||
* If {@link #addSingleItemCollectionBuilders()} and {@link #useImmutableCollections()} are enabled the builder
|
||||
* uses an internal class to track changes to maps. This is the name of that class.
|
||||
*/
|
||||
String mutableMapClassName() default "_MutableMap";
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.CLASS)
|
||||
|
||||
@@ -21,7 +21,8 @@ import java.lang.annotation.*;
|
||||
interpretNotNulls = true,
|
||||
useImmutableCollections = true,
|
||||
addSingleItemCollectionBuilders = true,
|
||||
addFunctionalMethodsToWith = true
|
||||
addFunctionalMethodsToWith = true,
|
||||
addClassRetainedGenerated = true
|
||||
))
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
@Target(ElementType.TYPE)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Copyright 2019 Jordan Zimmerman
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package io.soabase.recordbuilder.core;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.*;
|
||||
|
||||
/**
|
||||
* Jacoco ignores classes and methods annotated with `*Generated`
|
||||
*/
|
||||
@Target({PACKAGE, TYPE, METHOD, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, PARAMETER})
|
||||
@Retention(RetentionPolicy.CLASS)
|
||||
public @interface RecordBuilderGenerated {
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
<parent>
|
||||
<groupId>io.soabase.record-builder</groupId>
|
||||
<artifactId>record-builder</artifactId>
|
||||
<version>31</version>
|
||||
<version>34</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
||||
@@ -22,24 +22,38 @@ import javax.lang.model.element.Modifier;
|
||||
import java.util.*;
|
||||
|
||||
import static io.soabase.recordbuilder.processor.RecordBuilderProcessor.generatedRecordBuilderAnnotation;
|
||||
import static io.soabase.recordbuilder.processor.RecordBuilderProcessor.recordBuilderGeneratedAnnotation;
|
||||
|
||||
class CollectionBuilderUtils {
|
||||
private final boolean useImmutableCollections;
|
||||
private final boolean addSingleItemCollectionBuilders;
|
||||
private final boolean addClassRetainedGenerated;
|
||||
private final String listShimName;
|
||||
private final String mapShimName;
|
||||
private final String setShimName;
|
||||
private final String collectionShimName;
|
||||
|
||||
private final String listMakerMethodName;
|
||||
private final String mapMakerMethodName;
|
||||
private final String setMakerMethodName;
|
||||
|
||||
private boolean needsListShim;
|
||||
private boolean needsMapShim;
|
||||
private boolean needsSetShim;
|
||||
private boolean needsCollectionShim;
|
||||
|
||||
private static final TypeName listType = TypeName.get(List.class);
|
||||
private static final TypeName mapType = TypeName.get(Map.class);
|
||||
private static final TypeName setType = TypeName.get(Set.class);
|
||||
private static final TypeName collectionType = TypeName.get(Collection.class);
|
||||
private boolean needsListMutableMaker;
|
||||
private boolean needsMapMutableMaker;
|
||||
private boolean needsSetMutableMaker;
|
||||
|
||||
private static final Class<?> listType = List.class;
|
||||
private static final Class<?> mapType = Map.class;
|
||||
private static final Class<?> setType = Set.class;
|
||||
private static final Class<?> collectionType = Collection.class;
|
||||
private static final TypeName listTypeName = TypeName.get(listType);
|
||||
private static final TypeName mapTypeName = TypeName.get(mapType);
|
||||
private static final TypeName setTypeName = TypeName.get(setType);
|
||||
private static final TypeName collectionTypeName = TypeName.get(collectionType);
|
||||
|
||||
private static final TypeVariableName tType = TypeVariableName.get("T");
|
||||
private static final TypeVariableName kType = TypeVariableName.get("K");
|
||||
@@ -49,14 +63,33 @@ class CollectionBuilderUtils {
|
||||
private static final ParameterizedTypeName parameterizedSetType = ParameterizedTypeName.get(ClassName.get(Set.class), tType);
|
||||
private static final ParameterizedTypeName parameterizedCollectionType = ParameterizedTypeName.get(ClassName.get(Collection.class), tType);
|
||||
|
||||
private static final Class<?> mutableListType = ArrayList.class;
|
||||
private static final Class<?> mutableMapType = HashMap.class;
|
||||
private static final Class<?> mutableSetType = HashSet.class;
|
||||
private static final ClassName mutableListTypeName = ClassName.get(mutableListType);
|
||||
private static final ClassName mutableMapTypeName = ClassName.get(mutableMapType);
|
||||
private static final ClassName mutableSetTypeName = ClassName.get(mutableSetType);
|
||||
private final TypeSpec mutableListSpec;
|
||||
private final TypeSpec mutableSetSpec;
|
||||
private final TypeSpec mutableMapSpec;
|
||||
|
||||
CollectionBuilderUtils(List<RecordClassType> recordComponents, RecordBuilder.Options metaData) {
|
||||
useImmutableCollections = metaData.useImmutableCollections();
|
||||
addSingleItemCollectionBuilders = metaData.addSingleItemCollectionBuilders();
|
||||
addClassRetainedGenerated = metaData.addClassRetainedGenerated();
|
||||
|
||||
listShimName = adjustShimName(recordComponents, "__list", 0);
|
||||
mapShimName = adjustShimName(recordComponents, "__map", 0);
|
||||
setShimName = adjustShimName(recordComponents, "__set", 0);
|
||||
collectionShimName = adjustShimName(recordComponents, "__collection", 0);
|
||||
listShimName = disambiguateGeneratedMethodName(recordComponents, "__list", 0);
|
||||
mapShimName = disambiguateGeneratedMethodName(recordComponents, "__map", 0);
|
||||
setShimName = disambiguateGeneratedMethodName(recordComponents, "__set", 0);
|
||||
collectionShimName = disambiguateGeneratedMethodName(recordComponents, "__collection", 0);
|
||||
|
||||
listMakerMethodName = disambiguateGeneratedMethodName(recordComponents, "__ensureListMutable", 0);
|
||||
setMakerMethodName = disambiguateGeneratedMethodName(recordComponents, "__ensureSetMutable", 0);
|
||||
mapMakerMethodName = disambiguateGeneratedMethodName(recordComponents, "__ensureMapMutable", 0);
|
||||
|
||||
mutableListSpec = buildMutableCollectionSubType(metaData.mutableListClassName(), mutableListTypeName, parameterizedListType, tType);
|
||||
mutableSetSpec = buildMutableCollectionSubType(metaData.mutableSetClassName(), mutableSetTypeName, parameterizedSetType, tType);
|
||||
mutableMapSpec = buildMutableCollectionSubType(metaData.mutableMapClassName(), mutableMapTypeName, parameterizedMapType, kType, vType);
|
||||
}
|
||||
|
||||
enum SingleItemsMetaDataMode {
|
||||
@@ -65,7 +98,8 @@ class CollectionBuilderUtils {
|
||||
EXCLUDE_WILDCARD_TYPES
|
||||
}
|
||||
|
||||
record SingleItemsMetaData(Class<?> singleItemCollectionClass, List<TypeName> typeArguments, TypeName wildType) {}
|
||||
record SingleItemsMetaData(Class<?> singleItemCollectionClass, List<TypeName> typeArguments, TypeName wildType) {
|
||||
}
|
||||
|
||||
Optional<SingleItemsMetaData> singleItemsMetaData(RecordClassType component, SingleItemsMetaDataMode mode) {
|
||||
if (addSingleItemCollectionBuilders && (component.typeName() instanceof ParameterizedTypeName parameterizedTypeName)) {
|
||||
@@ -73,15 +107,15 @@ class CollectionBuilderUtils {
|
||||
ClassName wildcardClass = null;
|
||||
int typeArgumentQty = 0;
|
||||
if (isList(component)) {
|
||||
collectionClass = ArrayList.class;
|
||||
collectionClass = mutableListType;
|
||||
wildcardClass = ClassName.get(Collection.class);
|
||||
typeArgumentQty = 1;
|
||||
} else if (isSet(component)) {
|
||||
collectionClass = HashSet.class;
|
||||
collectionClass = mutableSetType;
|
||||
wildcardClass = ClassName.get(Collection.class);
|
||||
typeArgumentQty = 1;
|
||||
} else if (isMap(component)) {
|
||||
collectionClass = HashMap.class;
|
||||
collectionClass = mutableMapType;
|
||||
wildcardClass = (ClassName) component.rawTypeName();
|
||||
typeArgumentQty = 2;
|
||||
}
|
||||
@@ -109,30 +143,37 @@ class CollectionBuilderUtils {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
boolean isImmutableCollection(RecordClassType component) {
|
||||
return useImmutableCollections && (isList(component) || isMap(component) || isSet(component) || component.rawTypeName().equals(collectionTypeName));
|
||||
}
|
||||
|
||||
boolean isList(RecordClassType component) {
|
||||
return component.rawTypeName().equals(listType);
|
||||
return component.rawTypeName().equals(listTypeName);
|
||||
}
|
||||
|
||||
boolean isMap(RecordClassType component) {
|
||||
return component.rawTypeName().equals(mapType);
|
||||
return component.rawTypeName().equals(mapTypeName);
|
||||
}
|
||||
|
||||
boolean isSet(RecordClassType component) {
|
||||
return component.rawTypeName().equals(setType);
|
||||
return component.rawTypeName().equals(setTypeName);
|
||||
}
|
||||
|
||||
void add(CodeBlock.Builder builder, RecordClassType component) {
|
||||
void addShimCall(CodeBlock.Builder builder, RecordClassType component) {
|
||||
if (useImmutableCollections) {
|
||||
if (isList(component)) {
|
||||
needsListShim = true;
|
||||
needsListMutableMaker = true;
|
||||
builder.add("$L($L)", listShimName, component.name());
|
||||
} else if (isMap(component)) {
|
||||
needsMapShim = true;
|
||||
needsMapMutableMaker = true;
|
||||
builder.add("$L($L)", mapShimName, component.name());
|
||||
} else if (isSet(component)) {
|
||||
needsSetShim = true;
|
||||
needsSetMutableMaker = true;
|
||||
builder.add("$L($L)", setShimName, component.name());
|
||||
} else if (component.rawTypeName().equals(collectionType)) {
|
||||
} else if (component.rawTypeName().equals(collectionTypeName)) {
|
||||
needsCollectionShim = true;
|
||||
builder.add("$L($L)", collectionShimName, component.name());
|
||||
} else {
|
||||
@@ -143,22 +184,67 @@ class CollectionBuilderUtils {
|
||||
}
|
||||
}
|
||||
|
||||
String shimName(RecordClassType component) {
|
||||
if (isList(component)) {
|
||||
return listShimName;
|
||||
} else if (isMap(component)) {
|
||||
return mapShimName;
|
||||
} else if (isSet(component)) {
|
||||
return setShimName;
|
||||
} else if (component.rawTypeName().equals(collectionTypeName)) {
|
||||
return collectionShimName;
|
||||
} else {
|
||||
throw new IllegalArgumentException(component + " is not a supported collection type");
|
||||
}
|
||||
}
|
||||
|
||||
String mutableMakerName(RecordClassType component) {
|
||||
if (isList(component)) {
|
||||
return listMakerMethodName;
|
||||
} else if (isMap(component)) {
|
||||
return mapMakerMethodName;
|
||||
} else if (isSet(component)) {
|
||||
return setMakerMethodName;
|
||||
} else {
|
||||
throw new IllegalArgumentException(component + " is not a supported collection type");
|
||||
}
|
||||
}
|
||||
|
||||
void addShims(TypeSpec.Builder builder) {
|
||||
if (!useImmutableCollections) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (needsListShim) {
|
||||
builder.addMethod(buildMethod(listShimName, listType, parameterizedListType, tType));
|
||||
builder.addMethod(buildShimMethod(listShimName, listTypeName, collectionType, parameterizedListType, tType));
|
||||
}
|
||||
if (needsSetShim) {
|
||||
builder.addMethod(buildMethod(setShimName, setType, parameterizedSetType, tType));
|
||||
builder.addMethod(buildShimMethod(setShimName, setTypeName, collectionType, parameterizedSetType, tType));
|
||||
}
|
||||
if (needsMapShim) {
|
||||
builder.addMethod(buildMethod(mapShimName, mapType, parameterizedMapType, kType, vType));
|
||||
builder.addMethod(buildShimMethod(mapShimName, mapTypeName, mapType, parameterizedMapType, kType, vType));
|
||||
}
|
||||
if (needsCollectionShim) {
|
||||
builder.addMethod(buildCollectionsMethod());
|
||||
builder.addMethod(buildCollectionsShimMethod());
|
||||
}
|
||||
}
|
||||
|
||||
void addMutableMakers(TypeSpec.Builder builder) {
|
||||
if (!useImmutableCollections) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (needsListMutableMaker) {
|
||||
builder.addMethod(buildMutableMakerMethod(listMakerMethodName, mutableListSpec.name, parameterizedListType, tType));
|
||||
builder.addType(mutableListSpec);
|
||||
}
|
||||
if (needsSetMutableMaker) {
|
||||
builder.addMethod(buildMutableMakerMethod(setMakerMethodName, mutableSetSpec.name, parameterizedSetType, tType));
|
||||
builder.addType(mutableSetSpec);
|
||||
}
|
||||
if (needsMapMutableMaker) {
|
||||
builder.addMethod(buildMutableMakerMethod(mapMakerMethodName, mutableMapSpec.name, parameterizedMapType, kType, vType));
|
||||
builder.addType(mutableMapSpec);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,34 +269,71 @@ class CollectionBuilderUtils {
|
||||
return false;
|
||||
}
|
||||
|
||||
private String adjustShimName(List<RecordClassType> recordComponents, String baseName, int index) {
|
||||
private String disambiguateGeneratedMethodName(List<RecordClassType> recordComponents, String baseName, int index) {
|
||||
var name = (index == 0) ? baseName : (baseName + index);
|
||||
if (recordComponents.stream().anyMatch(component -> component.name().equals(name))) {
|
||||
return adjustShimName(recordComponents, baseName, index + 1);
|
||||
return disambiguateGeneratedMethodName(recordComponents, baseName, index + 1);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
private MethodSpec buildMethod(String name, TypeName mainType, ParameterizedTypeName parameterizedType, TypeVariableName... typeVariables) {
|
||||
private MethodSpec buildShimMethod(String name, TypeName mainType, Class<?> abstractType, ParameterizedTypeName parameterizedType, TypeVariableName... typeVariables) {
|
||||
var code = CodeBlock.of("return (o != null) ? $T.copyOf(o) : $T.of()", mainType, mainType);
|
||||
TypeName[] wildCardTypeArguments = parameterizedType.typeArguments.stream().map(WildcardTypeName::subtypeOf).toList().toArray(new TypeName[0]);
|
||||
var extendedParameterizedType = ParameterizedTypeName.get(ClassName.get(abstractType), wildCardTypeArguments);
|
||||
return MethodSpec.methodBuilder(name)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.addModifiers(Modifier.PRIVATE, Modifier.STATIC)
|
||||
.addTypeVariables(Arrays.asList(typeVariables))
|
||||
.returns(parameterizedType)
|
||||
.addParameter(extendedParameterizedType, "o")
|
||||
.addStatement(code)
|
||||
.build();
|
||||
}
|
||||
|
||||
private MethodSpec buildMutableMakerMethod(String name, String mutableCollectionType, ParameterizedTypeName parameterizedType, TypeVariableName... typeVariables) {
|
||||
var nullCase = CodeBlock.of("if (o == null) return new $L<>()", mutableCollectionType);
|
||||
var isMutableCase = CodeBlock.of("if (o instanceof $L) return o", mutableCollectionType);
|
||||
var defaultCase = CodeBlock.of("return new $L<>(o)", mutableCollectionType);
|
||||
return MethodSpec.methodBuilder(name)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.addModifiers(Modifier.PRIVATE, Modifier.STATIC)
|
||||
.addTypeVariables(Arrays.asList(typeVariables))
|
||||
.returns(parameterizedType)
|
||||
.addParameter(parameterizedType, "o")
|
||||
.addStatement(code)
|
||||
.addStatement(nullCase)
|
||||
.addStatement(isMutableCase)
|
||||
.addStatement(defaultCase)
|
||||
.build();
|
||||
}
|
||||
|
||||
private MethodSpec buildCollectionsMethod() {
|
||||
private TypeSpec buildMutableCollectionSubType(String className, ClassName mutableCollectionType, ParameterizedTypeName parameterizedType, TypeVariableName... typeVariables) {
|
||||
TypeName[] typeArguments = new TypeName[]{};
|
||||
typeArguments = Arrays.stream(typeVariables).toList().toArray(typeArguments);
|
||||
|
||||
TypeSpec.Builder builder = TypeSpec.classBuilder(className)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.addModifiers(Modifier.PRIVATE, Modifier.STATIC)
|
||||
.superclass(ParameterizedTypeName.get(mutableCollectionType, typeArguments))
|
||||
.addTypeVariables(Arrays.asList(typeVariables))
|
||||
.addMethod(MethodSpec.constructorBuilder().addAnnotation(generatedRecordBuilderAnnotation).addStatement("super()").build())
|
||||
.addMethod(MethodSpec.constructorBuilder().addAnnotation(generatedRecordBuilderAnnotation).addParameter(parameterizedType, "o").addStatement("super(o)").build());
|
||||
|
||||
if (addClassRetainedGenerated) {
|
||||
builder.addAnnotation(recordBuilderGeneratedAnnotation);
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private MethodSpec buildCollectionsShimMethod() {
|
||||
var code = CodeBlock.builder()
|
||||
.add("if (o instanceof Set) {\n")
|
||||
.indent()
|
||||
.addStatement("return $T.copyOf(o)", setType)
|
||||
.addStatement("return $T.copyOf(o)", setTypeName)
|
||||
.unindent()
|
||||
.addStatement("}")
|
||||
.addStatement("return (o != null) ? $T.copyOf(o) : $T.of()", listType, listType)
|
||||
.addStatement("return (o != null) ? $T.copyOf(o) : $T.of()", listTypeName, listTypeName)
|
||||
.build();
|
||||
return MethodSpec.methodBuilder(collectionShimName)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
|
||||
@@ -15,22 +15,26 @@
|
||||
*/
|
||||
package io.soabase.recordbuilder.processor;
|
||||
|
||||
import com.squareup.javapoet.*;
|
||||
import io.soabase.recordbuilder.core.RecordBuilder;
|
||||
import static io.soabase.recordbuilder.processor.CollectionBuilderUtils.SingleItemsMetaDataMode.EXCLUDE_WILDCARD_TYPES;
|
||||
import static io.soabase.recordbuilder.processor.CollectionBuilderUtils.SingleItemsMetaDataMode.STANDARD_FOR_SETTER;
|
||||
import static io.soabase.recordbuilder.processor.ElementUtils.getBuilderName;
|
||||
import static io.soabase.recordbuilder.processor.ElementUtils.getWithMethodName;
|
||||
import static io.soabase.recordbuilder.processor.RecordBuilderProcessor.generatedRecordBuilderAnnotation;
|
||||
import static io.soabase.recordbuilder.processor.RecordBuilderProcessor.recordBuilderGeneratedAnnotation;
|
||||
|
||||
import javax.annotation.processing.ProcessingEnvironment;
|
||||
import javax.lang.model.element.*;
|
||||
import java.util.*;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static io.soabase.recordbuilder.processor.CollectionBuilderUtils.SingleItemsMetaDataMode.*;
|
||||
import static io.soabase.recordbuilder.processor.ElementUtils.getBuilderName;
|
||||
import static io.soabase.recordbuilder.processor.ElementUtils.getWithMethodName;
|
||||
import static io.soabase.recordbuilder.processor.RecordBuilderProcessor.generatedRecordBuilderAnnotation;
|
||||
import com.squareup.javapoet.*;
|
||||
import io.soabase.recordbuilder.core.RecordBuilder;
|
||||
|
||||
class InternalRecordBuilderProcessor {
|
||||
private final RecordBuilder.Options metaData;
|
||||
@@ -46,10 +50,7 @@ class InternalRecordBuilderProcessor {
|
||||
private final CollectionBuilderUtils collectionBuilderUtils;
|
||||
|
||||
private static final TypeName overrideType = TypeName.get(Override.class);
|
||||
private static final TypeName optionalType = TypeName.get(Optional.class);
|
||||
private static final TypeName optionalIntType = TypeName.get(OptionalInt.class);
|
||||
private static final TypeName optionalLongType = TypeName.get(OptionalLong.class);
|
||||
private static final TypeName optionalDoubleType = TypeName.get(OptionalDouble.class);
|
||||
private static final TypeName validType = ClassName.get("javax.validation", "Valid");
|
||||
private static final TypeName validatorTypeName = ClassName.get("io.soabase.recordbuilder.validator", "RecordBuilderValidator");
|
||||
private static final TypeVariableName rType = TypeVariableName.get("R");
|
||||
private final ProcessingEnvironment processingEnv;
|
||||
@@ -70,16 +71,28 @@ class InternalRecordBuilderProcessor {
|
||||
builder = TypeSpec.classBuilder(builderClassType.name())
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.addTypeVariables(typeVariables);
|
||||
if (metaData.addClassRetainedGenerated()) {
|
||||
builder.addAnnotation(recordBuilderGeneratedAnnotation);
|
||||
}
|
||||
addVisibility(recordActualPackage.equals(packageName), record.getModifiers());
|
||||
addWithNestedClass();
|
||||
if (metaData.enableWither()) {
|
||||
addWithNestedClass();
|
||||
}
|
||||
if (!metaData.beanClassName().isEmpty()) {
|
||||
addBeanNestedClass();
|
||||
}
|
||||
addDefaultConstructor();
|
||||
addStaticBuilder();
|
||||
if (metaData.addStaticBuilder()) {
|
||||
addStaticBuilder();
|
||||
}
|
||||
if (recordComponents.size() > 0) {
|
||||
addAllArgsConstructor();
|
||||
}
|
||||
addStaticDefaultBuilderMethod();
|
||||
addStaticCopyBuilderMethod();
|
||||
addStaticFromWithMethod();
|
||||
if (metaData.enableWither()) {
|
||||
addStaticFromWithMethod();
|
||||
}
|
||||
addStaticComponentsMethod();
|
||||
addBuildMethod();
|
||||
addToStringMethod();
|
||||
@@ -88,11 +101,17 @@ class InternalRecordBuilderProcessor {
|
||||
recordComponents.forEach(component -> {
|
||||
add1Field(component);
|
||||
add1SetterMethod(component);
|
||||
add1GetterMethod(component);
|
||||
if (metaData.enableGetters()) {
|
||||
add1GetterMethod(component);
|
||||
}
|
||||
if (metaData.addConcreteSettersForOptional()) {
|
||||
add1ConcreteOptionalSetterMethod(component);
|
||||
}
|
||||
var collectionMetaData = collectionBuilderUtils.singleItemsMetaData(component, EXCLUDE_WILDCARD_TYPES);
|
||||
collectionMetaData.ifPresent(meta -> add1CollectionBuilders(meta, component));
|
||||
});
|
||||
collectionBuilderUtils.addShims(builder);
|
||||
collectionBuilderUtils.addMutableMakers(builder);
|
||||
builderType = builder.build();
|
||||
}
|
||||
|
||||
@@ -147,7 +166,10 @@ class InternalRecordBuilderProcessor {
|
||||
.addJavadoc("Add withers to {@code $L}\n", recordClassType.name())
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addTypeVariables(typeVariables);
|
||||
recordComponents.forEach(component -> addNestedGetterMethod(classBuilder, component));
|
||||
if (metaData.addClassRetainedGenerated()) {
|
||||
classBuilder.addAnnotation(recordBuilderGeneratedAnnotation);
|
||||
}
|
||||
recordComponents.forEach(component -> addNestedGetterMethod(classBuilder, component, prefixedName(component, true)));
|
||||
addWithBuilderMethod(classBuilder);
|
||||
addWithSuppliedBuilderMethod(classBuilder);
|
||||
IntStream.range(0, recordComponents.size()).forEach(index -> add1WithMethod(classBuilder, recordComponents.get(index), index));
|
||||
@@ -160,6 +182,31 @@ class InternalRecordBuilderProcessor {
|
||||
builder.addType(classBuilder.build());
|
||||
}
|
||||
|
||||
private void addBeanNestedClass() {
|
||||
/*
|
||||
Adds a nested interface that adds getters similar to:
|
||||
|
||||
public class MyRecordBuilder {
|
||||
public interface Bean {
|
||||
// getter methods
|
||||
}
|
||||
}
|
||||
*/
|
||||
var classBuilder = TypeSpec.interfaceBuilder(metaData.beanClassName())
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.addJavadoc("Add getters to {@code $L}\n", recordClassType.name())
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addTypeVariables(typeVariables);
|
||||
recordComponents.forEach(component -> {
|
||||
if (prefixedName(component, true).equals(component.name())) {
|
||||
return;
|
||||
}
|
||||
addNestedGetterMethod(classBuilder, component, component.name());
|
||||
add1PrefixedGetterMethod(classBuilder, component);
|
||||
});
|
||||
builder.addType(classBuilder.build());
|
||||
}
|
||||
|
||||
private void addWithSuppliedBuilderMethod(TypeSpec.Builder classBuilder) {
|
||||
/*
|
||||
Adds a method that returns a pre-filled copy builder similar to:
|
||||
@@ -196,7 +243,7 @@ class InternalRecordBuilderProcessor {
|
||||
}
|
||||
*/
|
||||
var codeBlockBuilder = CodeBlock.builder()
|
||||
.add("return new $L(", builderClassType.name());
|
||||
.add("return new $L$L(", builderClassType.name(), typeVariables.isEmpty() ? "" : "<>");
|
||||
addComponentCallsAsArguments(-1, codeBlockBuilder);
|
||||
codeBlockBuilder.add(");");
|
||||
var methodSpec = MethodSpec.methodBuilder(metaData.withClassMethodPrefix())
|
||||
@@ -257,6 +304,28 @@ class InternalRecordBuilderProcessor {
|
||||
classBuilder.addMethod(methodSpec);
|
||||
}
|
||||
|
||||
private void add1PrefixedGetterMethod(TypeSpec.Builder classBuilder, RecordClassType component) {
|
||||
/*
|
||||
Adds a get method for the component similar to:
|
||||
|
||||
default MyRecord getName() {
|
||||
return name();
|
||||
}
|
||||
*/
|
||||
var codeBlockBuilder = CodeBlock.builder();
|
||||
codeBlockBuilder.add("$[return $L()$];", component.name());
|
||||
|
||||
var methodName = prefixedName(component, true);
|
||||
var methodSpec = MethodSpec.methodBuilder(methodName)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.addJavadoc("Returns the value of {@code $L}\n", component.name())
|
||||
.addModifiers(Modifier.PUBLIC, Modifier.DEFAULT)
|
||||
.addCode(codeBlockBuilder.build())
|
||||
.returns(component.typeName())
|
||||
.build();
|
||||
classBuilder.addMethod(methodSpec);
|
||||
}
|
||||
|
||||
private void addComponentCallsAsArguments(int index, CodeBlock.Builder codeBlockBuilder) {
|
||||
IntStream.range(0, recordComponents.size()).forEach(parameterIndex -> {
|
||||
if (parameterIndex > 0) {
|
||||
@@ -264,9 +333,9 @@ class InternalRecordBuilderProcessor {
|
||||
}
|
||||
RecordClassType parameterComponent = recordComponents.get(parameterIndex);
|
||||
if (parameterIndex == index) {
|
||||
collectionBuilderUtils.add(codeBlockBuilder, parameterComponent);
|
||||
collectionBuilderUtils.addShimCall(codeBlockBuilder, parameterComponent);
|
||||
} else {
|
||||
codeBlockBuilder.add("$L()", parameterComponent.name());
|
||||
codeBlockBuilder.add("$L()", prefixedName(parameterComponent, true));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -320,8 +389,10 @@ class InternalRecordBuilderProcessor {
|
||||
private void addNullCheckCodeBlock(CodeBlock.Builder builder, int index) {
|
||||
if (metaData.interpretNotNulls()) {
|
||||
var component = recordComponents.get(index);
|
||||
if (!component.typeName().isPrimitive() && isNullAnnotated(component)) {
|
||||
builder.addStatement("$T.requireNonNull($L, $S)", Objects.class, component.name(), component.name() + " is required");
|
||||
if (!collectionBuilderUtils.isImmutableCollection(component)) {
|
||||
if (!component.typeName().isPrimitive() && isNullAnnotated(component)) {
|
||||
builder.addStatement("$T.requireNonNull($L, $S)", Objects.class, component.name(), component.name() + " is required");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -346,9 +417,7 @@ class InternalRecordBuilderProcessor {
|
||||
.addAnnotation(generatedRecordBuilderAnnotation);
|
||||
recordComponents.forEach(component -> {
|
||||
constructorBuilder.addParameter(component.typeName(), component.name());
|
||||
var collectionMetaData = collectionBuilderUtils.singleItemsMetaData(component, STANDARD);
|
||||
collectionMetaData.ifPresentOrElse(meta -> constructorBuilder.addStatement("this.$L = new $T<>($L)", component.name(), meta.singleItemCollectionClass(), component.name()),
|
||||
() -> constructorBuilder.addStatement("this.$L = $L", component.name(), component.name()));
|
||||
constructorBuilder.addStatement("this.$L = $L", component.name(), component.name());
|
||||
});
|
||||
builder.addMethod(constructorBuilder.build());
|
||||
}
|
||||
@@ -423,7 +492,12 @@ class InternalRecordBuilderProcessor {
|
||||
*/
|
||||
var codeBuilder = CodeBlock.builder();
|
||||
codeBuilder.add("return (this == o) || (");
|
||||
codeBuilder.add("(o instanceof $L $L)", builderClassType.name(), uniqueVarName);
|
||||
if (typeVariables.isEmpty()) {
|
||||
codeBuilder.add("(o instanceof $L $L)", builderClassType.name(), uniqueVarName);
|
||||
} else {
|
||||
String wildcardList = typeVariables.stream().map(__ -> "?").collect(Collectors.joining(","));
|
||||
codeBuilder.add("(o instanceof $L<$L> $L)", builderClassType.name(), wildcardList, uniqueVarName);
|
||||
}
|
||||
recordComponents.forEach(recordComponent -> {
|
||||
String name = recordComponent.name();
|
||||
if (recordComponent.typeName().isPrimitive()) {
|
||||
@@ -470,6 +544,16 @@ class InternalRecordBuilderProcessor {
|
||||
*/
|
||||
|
||||
var codeBuilder = CodeBlock.builder();
|
||||
|
||||
IntStream.range(0, recordComponents.size()).forEach(index -> {
|
||||
var recordComponent = recordComponents.get(index);
|
||||
if (collectionBuilderUtils.isImmutableCollection(recordComponent)) {
|
||||
codeBuilder.add("$[$L = ", recordComponent.name());
|
||||
collectionBuilderUtils.addShimCall(codeBuilder, recordComponents.get(index));
|
||||
codeBuilder.add(";\n$]");
|
||||
}
|
||||
});
|
||||
|
||||
addNullCheckCodeBlock(codeBuilder);
|
||||
codeBuilder.add("$[return ");
|
||||
if (metaData.useValidationApi()) {
|
||||
@@ -480,7 +564,7 @@ class InternalRecordBuilderProcessor {
|
||||
if (index > 0) {
|
||||
codeBuilder.add(", ");
|
||||
}
|
||||
collectionBuilderUtils.add(codeBuilder, recordComponents.get(index));
|
||||
codeBuilder.add("$L", recordComponents.get(index).name());
|
||||
});
|
||||
codeBuilder.add(")");
|
||||
if (metaData.useValidationApi()) {
|
||||
@@ -490,63 +574,85 @@ class InternalRecordBuilderProcessor {
|
||||
return codeBuilder.build();
|
||||
}
|
||||
|
||||
private TypeName buildWithTypeName()
|
||||
{
|
||||
ClassName rawTypeName = ClassName.get(packageName, builderClassType.name() + "." + metaData.withClassName());
|
||||
if (typeVariables.isEmpty()) {
|
||||
return rawTypeName;
|
||||
}
|
||||
return ParameterizedTypeName.get(rawTypeName, typeVariables.toArray(new TypeName[]{}));
|
||||
}
|
||||
|
||||
private void addFromWithClass() {
|
||||
/*
|
||||
Adds static private class that implements/proxies the Wither
|
||||
|
||||
private static final class _FromWith implements MyRecordBuilder.With {
|
||||
private final MyRecord from;
|
||||
|
||||
@Override
|
||||
public String p1() {
|
||||
return from.p1();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String p2() {
|
||||
return from.p2();
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
var fromWithClassBuilder = TypeSpec.classBuilder(metaData.fromWithClassName())
|
||||
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.addTypeVariables(typeVariables)
|
||||
.addSuperinterface(buildWithTypeName());
|
||||
if (metaData.addClassRetainedGenerated()) {
|
||||
fromWithClassBuilder.addAnnotation(recordBuilderGeneratedAnnotation);
|
||||
}
|
||||
|
||||
fromWithClassBuilder.addField(recordClassType.typeName(), "from", Modifier.PRIVATE, Modifier.FINAL);
|
||||
MethodSpec constructorSpec = MethodSpec.constructorBuilder()
|
||||
.addParameter(recordClassType.typeName(), "from")
|
||||
.addStatement("this.from = from")
|
||||
.addModifiers(Modifier.PRIVATE)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.build();
|
||||
fromWithClassBuilder.addMethod(constructorSpec);
|
||||
|
||||
IntStream.range(0, recordComponents.size()).forEach(index -> {
|
||||
var component = recordComponents.get(index);
|
||||
MethodSpec methodSpec = MethodSpec.methodBuilder(prefixedName(component, true))
|
||||
.returns(component.typeName())
|
||||
.addAnnotation(Override.class)
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addStatement("return from.$L()", component.name())
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.build();
|
||||
fromWithClassBuilder.addMethod(methodSpec);
|
||||
});
|
||||
this.builder.addType(fromWithClassBuilder.build());
|
||||
}
|
||||
|
||||
private void addStaticFromWithMethod() {
|
||||
/*
|
||||
Adds static method that returns a "with"er view of an existing record.
|
||||
|
||||
public static With from(MyRecord from) {
|
||||
return new MyRecordBuilder.With() {
|
||||
@Override
|
||||
public String p1() {
|
||||
return from.p1();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String p2() {
|
||||
return from.p2();
|
||||
}
|
||||
};
|
||||
return new _FromWith(from);
|
||||
}
|
||||
*/
|
||||
var witherClassNameBuilder = CodeBlock.builder()
|
||||
.add("$L.$L", builderClassType.name(), metaData.withClassName());
|
||||
if (!typeVariables.isEmpty()) {
|
||||
witherClassNameBuilder.add("<");
|
||||
IntStream.range(0, typeVariables.size()).forEach(index -> {
|
||||
if (index > 0) {
|
||||
witherClassNameBuilder.add(", ");
|
||||
}
|
||||
witherClassNameBuilder.add(typeVariables.get(index).name);
|
||||
});
|
||||
witherClassNameBuilder.add(">");
|
||||
}
|
||||
var witherClassName = witherClassNameBuilder.build().toString();
|
||||
var codeBuilder = CodeBlock.builder()
|
||||
.add("return new $L", witherClassName)
|
||||
.add("() {\n").indent();
|
||||
IntStream.range(0, recordComponents.size()).forEach(index -> {
|
||||
var component = recordComponents.get(index);
|
||||
if (index > 0) {
|
||||
codeBuilder.add("\n");
|
||||
}
|
||||
codeBuilder.add("@Override\n")
|
||||
.add("public $T $L() {\n", component.typeName(), component.name())
|
||||
.indent()
|
||||
.addStatement("return from.$L()", component.name())
|
||||
.unindent()
|
||||
.add("}\n");
|
||||
});
|
||||
codeBuilder.unindent().addStatement("}");
|
||||
|
||||
var withType = ClassName.get("", witherClassName);
|
||||
var methodSpec = MethodSpec.methodBuilder("from")//metaData.copyMethodName())
|
||||
addFromWithClass();
|
||||
|
||||
var methodSpec = MethodSpec.methodBuilder(metaData.fromMethodName())
|
||||
.addJavadoc("Return a \"with\"er for an existing record instance\n")
|
||||
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.addTypeVariables(typeVariables)
|
||||
.addParameter(recordClassType.typeName(), metaData.fromMethodName())
|
||||
.returns(withType)
|
||||
.addCode(codeBuilder.build())
|
||||
.returns(buildWithTypeName())
|
||||
.addStatement("return new $L$L(from)", metaData.fromWithClassName(), typeVariables.isEmpty() ? "" : "<>")
|
||||
.build();
|
||||
builder.addMethod(methodSpec);
|
||||
}
|
||||
@@ -639,43 +745,29 @@ class InternalRecordBuilderProcessor {
|
||||
*/
|
||||
var fieldSpecBuilder = FieldSpec.builder(component.typeName(), component.name(), Modifier.PRIVATE);
|
||||
if (metaData.emptyDefaultForOptional()) {
|
||||
TypeName thisOptionalType = null;
|
||||
if (isOptional(component)) {
|
||||
thisOptionalType = optionalType;
|
||||
} else if (component.typeName().equals(optionalIntType)) {
|
||||
thisOptionalType = optionalIntType;
|
||||
} else if (component.typeName().equals(optionalLongType)) {
|
||||
thisOptionalType = optionalLongType;
|
||||
} else if (component.typeName().equals(optionalDoubleType)) {
|
||||
thisOptionalType = optionalDoubleType;
|
||||
}
|
||||
if (thisOptionalType != null) {
|
||||
var codeBlock = CodeBlock.builder().add("$T.empty()", thisOptionalType).build();
|
||||
Optional<OptionalType> thisOptionalType = OptionalType.fromClassType(component);
|
||||
if (thisOptionalType.isPresent()) {
|
||||
var codeBlock = CodeBlock.builder()
|
||||
.add("$T.empty()", thisOptionalType.get().typeName())
|
||||
.build();
|
||||
fieldSpecBuilder.initializer(codeBlock);
|
||||
}
|
||||
}
|
||||
builder.addField(fieldSpecBuilder.build());
|
||||
}
|
||||
|
||||
private boolean isOptional(ClassType component) {
|
||||
if (component.typeName().equals(optionalType)) {
|
||||
return true;
|
||||
}
|
||||
return (component.typeName() instanceof ParameterizedTypeName parameterizedTypeName) && parameterizedTypeName.rawType.equals(optionalType);
|
||||
}
|
||||
|
||||
private void addNestedGetterMethod(TypeSpec.Builder classBuilder, RecordClassType component) {
|
||||
private void addNestedGetterMethod(TypeSpec.Builder classBuilder, RecordClassType component, String methodName) {
|
||||
/*
|
||||
For a single record component, add a getter similar to:
|
||||
|
||||
T p();
|
||||
*/
|
||||
var methodSpecBuilder = MethodSpec.methodBuilder(component.name())
|
||||
var methodSpecBuilder = MethodSpec.methodBuilder(methodName)
|
||||
.addJavadoc("Return the current value for the {@code $L} record component in the builder\n", component.name())
|
||||
.addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.returns(component.typeName());
|
||||
addAccessorAnnotations(component, methodSpecBuilder);
|
||||
addAccessorAnnotations(component, methodSpecBuilder, this::filterOutValid);
|
||||
classBuilder.addMethod(methodSpecBuilder.build());
|
||||
}
|
||||
|
||||
@@ -683,6 +775,10 @@ class InternalRecordBuilderProcessor {
|
||||
return !annotationSpec.type.equals(overrideType);
|
||||
}
|
||||
|
||||
private boolean filterOutValid(AnnotationSpec annotationSpec) {
|
||||
return !annotationSpec.type.equals(validType);
|
||||
}
|
||||
|
||||
private void addConstructorAnnotations(RecordClassType component, ParameterSpec.Builder parameterSpecBuilder) {
|
||||
if (metaData.inheritComponentAnnotations()) {
|
||||
component.getCanonicalConstructorAnnotations()
|
||||
@@ -693,12 +789,13 @@ class InternalRecordBuilderProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
private void addAccessorAnnotations(RecordClassType component, MethodSpec.Builder methodSpecBuilder) {
|
||||
private void addAccessorAnnotations(RecordClassType component, MethodSpec.Builder methodSpecBuilder, Predicate<AnnotationSpec> additionalFilter) {
|
||||
if (metaData.inheritComponentAnnotations()) {
|
||||
component.getAccessorAnnotations()
|
||||
.stream()
|
||||
.map(AnnotationSpec::get)
|
||||
.filter(this::filterOutOverride)
|
||||
.filter(additionalFilter)
|
||||
.forEach(methodSpecBuilder::addAnnotation);
|
||||
}
|
||||
}
|
||||
@@ -720,34 +817,34 @@ class InternalRecordBuilderProcessor {
|
||||
For a single map record component, add a methods similar to:
|
||||
|
||||
public T addP(K key, V value) {
|
||||
if (this.p == null) {
|
||||
this.p = new HashMap<>();
|
||||
}
|
||||
this.p = __ensureMapMutable(p);
|
||||
this.p.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public T addP(Stream<? extends Map.Entry<K, V> i) {
|
||||
if (p == null) {
|
||||
p = new HashMap<>();
|
||||
}
|
||||
this.p = __ensureMapMutable(p);
|
||||
i.forEach(this.p::put);
|
||||
return this;
|
||||
}
|
||||
|
||||
public T addP(Iterable<? extends Map.Entry<K, V> i) {
|
||||
if (p == null) {
|
||||
p = new HashMap<>();
|
||||
}
|
||||
this.p = __ensureMapMutable(p);
|
||||
i.forEach(this.p::put);
|
||||
return this;
|
||||
}
|
||||
*/
|
||||
for (var i = 0; i < 3; ++i) {
|
||||
var codeBlockBuilder = CodeBlock.builder()
|
||||
.beginControlFlow("if (this.$L == null)", component.name())
|
||||
.addStatement("this.$L = new $T<>()", component.name(), HashMap.class)
|
||||
.endControlFlow();
|
||||
var codeBlockBuilder = CodeBlock.builder();
|
||||
if (collectionBuilderUtils.isImmutableCollection(component)) {
|
||||
codeBlockBuilder
|
||||
.addStatement("this.$L = $L($L)", component.name(), collectionBuilderUtils.mutableMakerName(component), component.name());
|
||||
} else {
|
||||
codeBlockBuilder
|
||||
.beginControlFlow("if (this.$L == null)", component.name())
|
||||
.addStatement("this.$L = new $T<>()", component.name(), meta.singleItemCollectionClass())
|
||||
.endControlFlow();
|
||||
}
|
||||
var methodSpecBuilder = MethodSpec.methodBuilder(metaData.singleItemBuilderPrefix() + capitalize(component.name()))
|
||||
.addJavadoc("Add to the internally allocated {@code HashMap} for {@code $L}\n", component.name())
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
@@ -775,25 +872,19 @@ class InternalRecordBuilderProcessor {
|
||||
For a single list or set record component, add methods similar to:
|
||||
|
||||
public T addP(I i) {
|
||||
if (this.p == null) {
|
||||
this.p = new ArrayList<>();
|
||||
}
|
||||
this.list = __ensureListMutable(list);
|
||||
this.p.add(i);
|
||||
return this;
|
||||
}
|
||||
|
||||
public T addP(Stream<? extends I> i) {
|
||||
if (this.p == null) {
|
||||
this.p = new ArrayList<>();
|
||||
}
|
||||
this.list = __ensureListMutable(list);
|
||||
this.p.addAll(i);
|
||||
return this;
|
||||
}
|
||||
|
||||
public T addP(Iterable<? extends I> i) {
|
||||
if (this.p == null) {
|
||||
this.p = new ArrayList<>();
|
||||
}
|
||||
this.list = __ensureListMutable(list);
|
||||
this.p.addAll(i);
|
||||
return this;
|
||||
}
|
||||
@@ -809,10 +900,17 @@ class InternalRecordBuilderProcessor {
|
||||
var parameterClass = ClassName.get((i == 1) ? Stream.class : Iterable.class);
|
||||
parameter = ParameterizedTypeName.get(parameterClass, WildcardTypeName.subtypeOf(meta.typeArguments().get(0)));
|
||||
}
|
||||
var codeBlockBuilder = CodeBlock.builder()
|
||||
.beginControlFlow("if (this.$L == null)", component.name())
|
||||
.addStatement("this.$L = new $T<>()", component.name(), meta.singleItemCollectionClass())
|
||||
.endControlFlow()
|
||||
var codeBlockBuilder = CodeBlock.builder();
|
||||
if (collectionBuilderUtils.isImmutableCollection(component)) {
|
||||
codeBlockBuilder
|
||||
.addStatement("this.$L = $L($L)", component.name(), collectionBuilderUtils.mutableMakerName(component), component.name());
|
||||
} else {
|
||||
codeBlockBuilder
|
||||
.beginControlFlow("if (this.$L == null)", component.name())
|
||||
.addStatement("this.$L = new $T<>()", component.name(), meta.singleItemCollectionClass())
|
||||
.endControlFlow();
|
||||
}
|
||||
codeBlockBuilder
|
||||
.add(addClockBlock.build())
|
||||
.addStatement("return this");
|
||||
var methodSpecBuilder = MethodSpec.methodBuilder(metaData.singleItemBuilderPrefix() + capitalize(component.name()))
|
||||
@@ -834,13 +932,13 @@ class InternalRecordBuilderProcessor {
|
||||
return p;
|
||||
}
|
||||
*/
|
||||
var methodSpecBuilder = MethodSpec.methodBuilder(component.name())
|
||||
var methodSpecBuilder = MethodSpec.methodBuilder(prefixedName(component, true))
|
||||
.addJavadoc("Return the current value for the {@code $L} record component in the builder\n", component.name())
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.returns(component.typeName())
|
||||
.addStatement("return $L", component.name());
|
||||
addAccessorAnnotations(component, methodSpecBuilder);
|
||||
addAccessorAnnotations(component, methodSpecBuilder, __ -> true);
|
||||
builder.addMethod(methodSpecBuilder.build());
|
||||
}
|
||||
|
||||
@@ -853,8 +951,7 @@ class InternalRecordBuilderProcessor {
|
||||
return this;
|
||||
}
|
||||
*/
|
||||
|
||||
var methodSpec = MethodSpec.methodBuilder(component.name())
|
||||
var methodSpec = MethodSpec.methodBuilder(prefixedName(component, false))
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.returns(builderClassType.typeName());
|
||||
@@ -862,8 +959,8 @@ class InternalRecordBuilderProcessor {
|
||||
var collectionMetaData = collectionBuilderUtils.singleItemsMetaData(component, STANDARD_FOR_SETTER);
|
||||
var parameterSpecBuilder = collectionMetaData.map(meta -> {
|
||||
CodeBlock.Builder codeSpec = CodeBlock.builder();
|
||||
codeSpec.addStatement("this.$L = ($L != null) ? new $T<>($L) : null", component.name(), component.name(), meta.singleItemCollectionClass(), component.name());
|
||||
methodSpec.addJavadoc("Re-create the internally allocated {@code $L} for {@code $L} by copying the argument\n", meta.singleItemCollectionClass().getSimpleName(), component.name())
|
||||
codeSpec.addStatement("this.$L = $L($L)", component.name(), collectionBuilderUtils.shimName(component), component.name());
|
||||
methodSpec.addJavadoc("Re-create the internally allocated {@code $T} for {@code $L} by copying the argument\n", component.typeName(), component.name())
|
||||
.addCode(codeSpec.build());
|
||||
return ParameterSpec.builder(meta.wildType(), component.name());
|
||||
}).orElseGet(() -> {
|
||||
@@ -876,6 +973,42 @@ class InternalRecordBuilderProcessor {
|
||||
builder.addMethod(methodSpec.build());
|
||||
}
|
||||
|
||||
private void add1ConcreteOptionalSetterMethod(RecordClassType component) {
|
||||
/*
|
||||
For a single optional record component, add a concrete setter similar to:
|
||||
|
||||
public MyRecordBuilder p(T p) {
|
||||
this.p = p;
|
||||
return this;
|
||||
}
|
||||
*/
|
||||
var optionalType = OptionalType.fromClassType(component);
|
||||
if (optionalType.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
var type = optionalType.get();
|
||||
var methodSpec = MethodSpec.methodBuilder(prefixedName(component, false))
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addAnnotation(generatedRecordBuilderAnnotation)
|
||||
.returns(builderClassType.typeName());
|
||||
|
||||
var parameterSpecBuilder = ParameterSpec.builder(type.valueType(), component.name());
|
||||
methodSpec.addJavadoc("Set a new value for the {@code $L} record component in the builder\n", component.name())
|
||||
.addStatement(getOptionalStatement(type), component.name(), type.typeName(), component.name());
|
||||
addConstructorAnnotations(component, parameterSpecBuilder);
|
||||
methodSpec.addStatement("return this").addParameter(parameterSpecBuilder.build());
|
||||
builder.addMethod(methodSpec.build());
|
||||
}
|
||||
|
||||
private String getOptionalStatement(OptionalType type) {
|
||||
|
||||
if(type.isOptional()) {
|
||||
return "this.$L = $T.ofNullable($L)";
|
||||
}
|
||||
|
||||
return "this.$L = $T.of($L)";
|
||||
}
|
||||
|
||||
private List<TypeVariableName> typeVariablesWithReturn() {
|
||||
var variables = new ArrayList<TypeVariableName>();
|
||||
variables.add(rType);
|
||||
@@ -940,5 +1073,18 @@ class InternalRecordBuilderProcessor {
|
||||
.addMethod(methodBuilder.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private String prefixedName(RecordClassType component, boolean isGetter) {
|
||||
BiFunction<String, String, String> prefixer = (p, s) -> p.isEmpty()
|
||||
? s : p + Character.toUpperCase(s.charAt(0)) + s.substring(1);
|
||||
boolean isBool = component.typeName().toString().toLowerCase(Locale.ROOT).equals("boolean");
|
||||
if (isGetter) {
|
||||
if (isBool) {
|
||||
return prefixer.apply(metaData.booleanPrefix(), component.name());
|
||||
}
|
||||
return prefixer.apply(metaData.getterPrefix(), component.name());
|
||||
}
|
||||
return prefixer.apply(metaData.setterPrefix(), component.name());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ import java.util.stream.Collectors;
|
||||
|
||||
import static io.soabase.recordbuilder.processor.ElementUtils.getBuilderName;
|
||||
import static io.soabase.recordbuilder.processor.RecordBuilderProcessor.generatedRecordInterfaceAnnotation;
|
||||
import static io.soabase.recordbuilder.processor.RecordBuilderProcessor.recordBuilderGeneratedAnnotation;
|
||||
|
||||
class InternalRecordInterfaceProcessor {
|
||||
private final ProcessingEnvironment processingEnv;
|
||||
@@ -68,6 +69,9 @@ class InternalRecordInterfaceProcessor {
|
||||
.addModifiers(Modifier.PUBLIC)
|
||||
.addAnnotation(generatedRecordInterfaceAnnotation)
|
||||
.addTypeVariables(typeVariables);
|
||||
if (metaData.addClassRetainedGenerated()) {
|
||||
builder.addAnnotation(recordBuilderGeneratedAnnotation);
|
||||
}
|
||||
|
||||
if (addRecordBuilder) {
|
||||
ClassType builderClassType = ElementUtils.getClassType(packageName, getBuilderName(iface, metaData, recordClassType, metaData.suffix()) + "." + metaData.withClassName(), iface.getTypeParameters());
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Copyright 2019 Jordan Zimmerman
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package io.soabase.recordbuilder.processor;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.OptionalLong;
|
||||
|
||||
import com.squareup.javapoet.ParameterizedTypeName;
|
||||
import com.squareup.javapoet.TypeName;
|
||||
|
||||
public record OptionalType(TypeName typeName, TypeName valueType) {
|
||||
|
||||
private static final TypeName optionalType = TypeName.get(Optional.class);
|
||||
private static final TypeName optionalIntType = TypeName.get(OptionalInt.class);
|
||||
private static final TypeName optionalLongType = TypeName.get(OptionalLong.class);
|
||||
private static final TypeName optionalDoubleType = TypeName.get(OptionalDouble.class);
|
||||
|
||||
private static boolean isOptional(ClassType component) {
|
||||
if (component.typeName().equals(optionalType)) {
|
||||
return true;
|
||||
}
|
||||
return (component.typeName() instanceof ParameterizedTypeName parameterizedTypeName)
|
||||
&& parameterizedTypeName.rawType.equals(optionalType);
|
||||
}
|
||||
|
||||
static Optional<OptionalType> fromClassType(final ClassType component) {
|
||||
if (isOptional(component)) {
|
||||
if (!(component.typeName() instanceof ParameterizedTypeName parameterizedType)) {
|
||||
return Optional.of(new OptionalType(optionalType, TypeName.get(Object.class)));
|
||||
}
|
||||
final TypeName containingType = parameterizedType.typeArguments.isEmpty()
|
||||
? TypeName.get(Object.class)
|
||||
: parameterizedType.typeArguments.get(0);
|
||||
return Optional.of(new OptionalType(optionalType, containingType));
|
||||
}
|
||||
if (component.typeName().equals(optionalIntType)) {
|
||||
return Optional.of(new OptionalType(optionalIntType, TypeName.get(int.class)));
|
||||
}
|
||||
if (component.typeName().equals(optionalLongType)) {
|
||||
return Optional.of(new OptionalType(optionalLongType, TypeName.get(long.class)));
|
||||
}
|
||||
if (component.typeName().equals(optionalDoubleType)) {
|
||||
return Optional.of(new OptionalType(optionalDoubleType, TypeName.get(double.class)));
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public boolean isOptional() {
|
||||
return typeName.equals(optionalType);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import com.squareup.javapoet.AnnotationSpec;
|
||||
import com.squareup.javapoet.JavaFile;
|
||||
import com.squareup.javapoet.TypeSpec;
|
||||
import io.soabase.recordbuilder.core.RecordBuilder;
|
||||
import io.soabase.recordbuilder.core.RecordBuilderGenerated;
|
||||
import io.soabase.recordbuilder.core.RecordInterface;
|
||||
|
||||
import javax.annotation.processing.AbstractProcessor;
|
||||
@@ -46,6 +47,7 @@ public class RecordBuilderProcessor
|
||||
|
||||
static final AnnotationSpec generatedRecordBuilderAnnotation = AnnotationSpec.builder(Generated.class).addMember("value", "$S", RecordBuilder.class.getName()).build();
|
||||
static final AnnotationSpec generatedRecordInterfaceAnnotation = AnnotationSpec.builder(Generated.class).addMember("value", "$S", RecordInterface.class.getName()).build();
|
||||
static final AnnotationSpec recordBuilderGeneratedAnnotation = AnnotationSpec.builder(RecordBuilderGenerated.class).build();
|
||||
|
||||
@Override
|
||||
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<parent>
|
||||
<groupId>io.soabase.record-builder</groupId>
|
||||
<artifactId>record-builder</artifactId>
|
||||
<version>31</version>
|
||||
<version>34</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
@@ -66,6 +66,48 @@
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>default-prepare-agent</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>default-report</id>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>default-check</id>
|
||||
<goals>
|
||||
<goal>check</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>io/soabase/recordbuilder/test/jacoco/*</include>
|
||||
</includes>
|
||||
<rules>
|
||||
<rule>
|
||||
<element>BUNDLE</element>
|
||||
<limits>
|
||||
<limit>
|
||||
<counter>COMPLEXITY</counter>
|
||||
<value>COVEREDRATIO</value>
|
||||
<minimum>0.60</minimum>
|
||||
</limit>
|
||||
</limits>
|
||||
</rule>
|
||||
</rules>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Copyright 2019 Jordan Zimmerman
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package io.soabase.recordbuilder.test;
|
||||
|
||||
import io.soabase.recordbuilder.core.RecordBuilder;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@RecordBuilder
|
||||
@RecordBuilder.Options(
|
||||
addSingleItemCollectionBuilders = true,
|
||||
useImmutableCollections = true,
|
||||
mutableListClassName = "PersonalizedMutableList"
|
||||
)
|
||||
public record CollectionCopying<T>(List<String> list, Set<T> set, Map<Instant, T> map, Collection<T> collection,
|
||||
int count) implements CollectionCopyingBuilder.With<T> {
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright 2019 Jordan Zimmerman
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package io.soabase.recordbuilder.test;
|
||||
|
||||
import java.util.List;
|
||||
import io.soabase.recordbuilder.core.RecordBuilder;
|
||||
import io.soabase.recordbuilder.test.CustomMethodNamesBuilder.Bean;
|
||||
|
||||
@RecordBuilder
|
||||
@RecordBuilder.Options(
|
||||
setterPrefix = "set", getterPrefix = "get", booleanPrefix = "is", beanClassName = "Bean")
|
||||
public record CustomMethodNames(
|
||||
int theValue,
|
||||
List<Integer> theList,
|
||||
boolean theBoolean) implements Bean {
|
||||
}
|
||||
@@ -22,5 +22,5 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RecordBuilderFull
|
||||
public record FullRecord(@NotNull List<Number> numbers, @NotNull Map<Number, FullRecord> fullRecords) {
|
||||
public record FullRecord(@NotNull List<Number> numbers, @NotNull Map<Number, FullRecord> fullRecords, @NotNull String justAString) {
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package io.soabase.recordbuilder.test;
|
||||
|
||||
import io.soabase.recordbuilder.core.RecordBuilder;
|
||||
|
||||
/**
|
||||
* Copyright 2019 Jordan Zimmerman
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
@RecordBuilder.Options(addStaticBuilder = false)
|
||||
@RecordBuilder
|
||||
public record NoStaticBuilder(String foo) {
|
||||
}
|
||||
@@ -15,6 +15,8 @@
|
||||
*/
|
||||
package io.soabase.recordbuilder.test;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
import io.soabase.recordbuilder.core.RecordBuilder;
|
||||
|
||||
import java.util.Optional;
|
||||
@@ -22,6 +24,6 @@ import java.util.OptionalDouble;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.OptionalLong;
|
||||
|
||||
@RecordBuilder.Options(emptyDefaultForOptional = true)
|
||||
@RecordBuilder.Options(emptyDefaultForOptional = true, addConcreteSettersForOptional = true)
|
||||
@RecordBuilder
|
||||
public record RecordWithOptional(Optional<String> value, Optional raw, OptionalInt i, OptionalLong l, OptionalDouble d) {}
|
||||
public record RecordWithOptional(@NotNull Optional<String> value, Optional raw, OptionalInt i, OptionalLong l, OptionalDouble d) {}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Copyright 2019 Jordan Zimmerman
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package io.soabase.recordbuilder.test;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.OptionalLong;
|
||||
import io.soabase.recordbuilder.core.RecordBuilder;
|
||||
|
||||
@RecordBuilder.Options(emptyDefaultForOptional = true)
|
||||
@RecordBuilder
|
||||
public record RecordWithOptional2(Optional<String> value, Optional raw, OptionalInt i, OptionalLong l, OptionalDouble d) {}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Copyright 2019 Jordan Zimmerman
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package io.soabase.recordbuilder.test;
|
||||
|
||||
import io.soabase.recordbuilder.core.RecordBuilder;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@RecordBuilder
|
||||
@RecordBuilder.Options(useValidationApi = true)
|
||||
public record RequestWithValid(@NotNull @Valid Part part) implements RequestWithValidBuilder.With {
|
||||
public record Part(@NotBlank String name) {}
|
||||
}
|
||||
@@ -18,8 +18,9 @@ package io.soabase.recordbuilder.test;
|
||||
import io.soabase.recordbuilder.core.RecordBuilder;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
|
||||
@RecordBuilder.Options(interpretNotNulls = true)
|
||||
@RecordBuilder
|
||||
public record RequiredRecord(@NotNull String hey, @NotNull int i) implements RequiredRecordBuilder.With {
|
||||
public record RequiredRecord(@NotNull String hey, @NotNull int i, @NotNull List<String> l) implements RequiredRecordBuilder.With {
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Copyright 2019 Jordan Zimmerman
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package io.soabase.recordbuilder.test;
|
||||
|
||||
import io.soabase.recordbuilder.core.RecordBuilder;
|
||||
|
||||
@RecordBuilder
|
||||
@RecordBuilder.Options(
|
||||
enableGetters = false,
|
||||
enableWither = false
|
||||
)
|
||||
public record StrippedFeaturesRecord(int aField) {}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Copyright 2019 Jordan Zimmerman
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package io.soabase.recordbuilder.test.jacoco;
|
||||
|
||||
import io.soabase.recordbuilder.core.RecordBuilderFull;
|
||||
import io.soabase.recordbuilder.core.RecordBuilderGenerated;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RecordBuilderFull
|
||||
@RecordBuilderGenerated
|
||||
public record FullRecordForJacoco(@NotNull List<Number> numbers, @NotNull Map<Number, FullRecordForJacoco> fullRecords, @NotNull String justAString) {
|
||||
}
|
||||
@@ -27,7 +27,7 @@ class TestCollections {
|
||||
@Test
|
||||
void testRecordBuilderOptionsCopied() {
|
||||
try {
|
||||
assertNotNull(CollectionInterfaceRecordBuilder.class.getDeclaredMethod("__list", List.class));
|
||||
assertNotNull(CollectionInterfaceRecordBuilder.class.getDeclaredMethod("__list", Collection.class));
|
||||
} catch (NoSuchMethodException e) {
|
||||
Assertions.fail(e);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Copyright 2019 Jordan Zimmerman
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package io.soabase.recordbuilder.test;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
public class TestImmutableCollections {
|
||||
@Test
|
||||
public void testImmutableListNotCopiedWhenNotChanged() {
|
||||
var item = CollectionCopyingBuilder.<String>builder()
|
||||
.addList("a")
|
||||
.addList("b")
|
||||
.addList("c")
|
||||
.build();
|
||||
Assertions.assertEquals(item.list(), List.of("a", "b", "c"));
|
||||
|
||||
var oldList = item.list();
|
||||
|
||||
var copy = item.with()
|
||||
.count(1)
|
||||
.build();
|
||||
|
||||
Assertions.assertSame(oldList, copy.list());
|
||||
|
||||
var otherCopy = item.with()
|
||||
.count(2)
|
||||
.build();
|
||||
|
||||
Assertions.assertSame(oldList, otherCopy.list());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImmutableSetNotCopiedWhenNotChanged() {
|
||||
var item = CollectionCopyingBuilder.<String>builder()
|
||||
.addSet(Arrays.asList("1", "2", "3"))
|
||||
.build();
|
||||
Assertions.assertEquals(item.set(), Set.of("1", "2", "3"));
|
||||
|
||||
var oldSet = item.set();
|
||||
|
||||
var copy = item.with()
|
||||
.count(1)
|
||||
.build();
|
||||
|
||||
Assertions.assertSame(oldSet, copy.set());
|
||||
|
||||
var otherCopy = item.with()
|
||||
.count(2)
|
||||
.build();
|
||||
|
||||
Assertions.assertSame(oldSet, otherCopy.set());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImmutableCollectionNotCopiedWhenNotChanged() {
|
||||
var item = CollectionCopyingBuilder.<String>builder()
|
||||
.collection(List.of("foo", "bar", "baz"))
|
||||
.build();
|
||||
Assertions.assertEquals(item.collection(), List.of("foo", "bar", "baz"));
|
||||
|
||||
var oldCollection = item.collection();
|
||||
|
||||
var copy = item.with()
|
||||
.count(1)
|
||||
.build();
|
||||
|
||||
Assertions.assertSame(oldCollection, copy.collection());
|
||||
|
||||
var otherCopy = item.with()
|
||||
.count(2)
|
||||
.build();
|
||||
|
||||
Assertions.assertSame(oldCollection, otherCopy.collection());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImmutableMapNotCopiedWhenNotChanged() {
|
||||
var item = CollectionCopyingBuilder.<String>builder()
|
||||
.addMap(Instant.MAX, "future")
|
||||
.addMap(Instant.MIN, "before")
|
||||
.build();
|
||||
Assertions.assertEquals(item.map(), Map.of(Instant.MAX, "future", Instant.MIN, "before"));
|
||||
|
||||
var oldMap = item.map();
|
||||
|
||||
var copy = item.with()
|
||||
.count(1)
|
||||
.build();
|
||||
|
||||
Assertions.assertSame(oldMap, copy.map());
|
||||
|
||||
var otherCopy = item.with()
|
||||
.count(2)
|
||||
.build();
|
||||
|
||||
Assertions.assertSame(oldMap, otherCopy.map());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSourceListNotModified() {
|
||||
var item = new CollectionCopying<>(new ArrayList<>(), null, null, null, 0);
|
||||
var modifiedItem = CollectionCopyingBuilder.builder(item)
|
||||
.addList("a")
|
||||
.build();
|
||||
|
||||
Assertions.assertEquals(modifiedItem.list(), List.of("a"));
|
||||
Assertions.assertTrue(item.list().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSourceSetNotModified() {
|
||||
var item = new CollectionCopying<>(null, new HashSet<>(), null, null, 0);
|
||||
var modifiedItem = CollectionCopyingBuilder.builder(item)
|
||||
.addSet("a")
|
||||
.build();
|
||||
|
||||
Assertions.assertEquals(modifiedItem.set(), Set.of("a"));
|
||||
Assertions.assertTrue(item.set().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSourceMapNotModified() {
|
||||
var item = new CollectionCopying<>(null, null, new HashMap<>(), null, 0);
|
||||
var modifiedItem = CollectionCopyingBuilder.builder(item)
|
||||
.addMap(Instant.MIN, "a")
|
||||
.build();
|
||||
|
||||
Assertions.assertEquals(modifiedItem.map(), Map.of(Instant.MIN, "a"));
|
||||
Assertions.assertTrue(item.map().isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -15,14 +15,14 @@
|
||||
*/
|
||||
package io.soabase.recordbuilder.test;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.OptionalLong;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class TestOptional {
|
||||
@Test
|
||||
void testDefaultEmpty() {
|
||||
@@ -33,4 +33,51 @@ class TestOptional {
|
||||
Assertions.assertEquals(OptionalLong.empty(), record.l());
|
||||
Assertions.assertEquals(OptionalDouble.empty(), record.d());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRawSetters() {
|
||||
var record = RecordWithOptionalBuilder.builder()
|
||||
.value("value")
|
||||
.raw("rawValue")
|
||||
.i(42)
|
||||
.l(424242L)
|
||||
.d(42.42)
|
||||
.build();
|
||||
Assertions.assertEquals(Optional.of("value"), record.value());
|
||||
Assertions.assertEquals(Optional.of("rawValue"), record.raw());
|
||||
Assertions.assertEquals(OptionalInt.of(42), record.i());
|
||||
Assertions.assertEquals(OptionalLong.of(424242L), record.l());
|
||||
Assertions.assertEquals(OptionalDouble.of(42.42), record.d());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOptionalSetters() {
|
||||
var record = RecordWithOptional2Builder.builder()
|
||||
.value(Optional.of("value"))
|
||||
.raw(Optional.of("rawValue"))
|
||||
.i(OptionalInt.of(42))
|
||||
.l(OptionalLong.of(424242L))
|
||||
.d(OptionalDouble.of(42.42))
|
||||
.build();
|
||||
Assertions.assertEquals(Optional.of("value"), record.value());
|
||||
Assertions.assertEquals(Optional.of("rawValue"), record.raw());
|
||||
Assertions.assertEquals(OptionalInt.of(42), record.i());
|
||||
Assertions.assertEquals(OptionalLong.of(424242L), record.l());
|
||||
Assertions.assertEquals(OptionalDouble.of(42.42), record.d());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAcceptNullForOptionalRawSetter() {
|
||||
// given
|
||||
String value = null;
|
||||
|
||||
// when
|
||||
var record = RecordWithOptionalBuilder.builder()
|
||||
.value(value)
|
||||
.build();
|
||||
|
||||
// then
|
||||
Assertions.assertEquals(Optional.empty(), record.value());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -20,11 +20,15 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
class TestRecordBuilderFull {
|
||||
@Test
|
||||
void testNonNull() {
|
||||
Assertions.assertThrows(NullPointerException.class, () -> FullRecordBuilder.builder().build());
|
||||
var record = FullRecordBuilder.builder().justAString("").build();
|
||||
Assertions.assertEquals(List.of(), record.numbers());
|
||||
Assertions.assertEquals(Map.of(), record.fullRecords());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -32,6 +36,7 @@ class TestRecordBuilderFull {
|
||||
var record = FullRecordBuilder.builder()
|
||||
.fullRecords(new HashMap<>())
|
||||
.numbers(new ArrayList<>())
|
||||
.justAString("")
|
||||
.build();
|
||||
Assertions.assertThrows(UnsupportedOperationException.class, () -> record.fullRecords().put(1, record));
|
||||
Assertions.assertThrows(UnsupportedOperationException.class, () -> record.numbers().add(1));
|
||||
|
||||
@@ -19,6 +19,7 @@ import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.validation.ValidationException;
|
||||
import java.util.List;
|
||||
|
||||
class TestValidation {
|
||||
@Test
|
||||
@@ -33,7 +34,7 @@ class TestValidation {
|
||||
|
||||
@Test
|
||||
void testNotNullsWithNewProperty() {
|
||||
var valid = RequiredRecordBuilder.builder().hey("hey").i(1).build();
|
||||
var valid = RequiredRecordBuilder.builder().hey("hey").i(1).l(List.of()).build();
|
||||
Assertions.assertThrows(NullPointerException.class, () -> valid.withHey(null));
|
||||
}
|
||||
|
||||
@@ -42,4 +43,14 @@ class TestValidation {
|
||||
var valid = RequiredRecord2Builder.builder().hey("hey").i(1).build();
|
||||
Assertions.assertThrows(ValidationException.class, () -> valid.withHey(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRequestWithValid() {
|
||||
Assertions.assertDoesNotThrow(() -> RequestWithValidBuilder.builder()
|
||||
.part(new RequestWithValid.Part("jsfjsf"))
|
||||
.build());
|
||||
Assertions.assertThrows(ValidationException.class, () -> RequestWithValidBuilder.builder()
|
||||
.part(new RequestWithValid.Part(""))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Copyright 2019 Jordan Zimmerman
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package io.soabase.recordbuilder.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestVariousOptions {
|
||||
|
||||
@Test
|
||||
public void builderGetsCustomSetterAndGetterNames() {
|
||||
var obj = CustomMethodNamesBuilder.builder()
|
||||
.setTheValue(1)
|
||||
.setTheList(List.of(2))
|
||||
.setTheBoolean(true);
|
||||
assertEquals(1, obj.getTheValue());
|
||||
assertEquals(List.of(2), obj.getTheList());
|
||||
assertTrue(obj.isTheBoolean());
|
||||
assertEquals(new CustomMethodNames(1, List.of(2), true), obj.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withBuilderGetsCustomSetterAndGetterNames() {
|
||||
var obj = CustomMethodNamesBuilder.from(CustomMethodNamesBuilder.builder()
|
||||
.setTheValue(1)
|
||||
.setTheList(List.of(2))
|
||||
.setTheBoolean(true)
|
||||
.build());
|
||||
assertEquals(1, obj.getTheValue());
|
||||
assertEquals(List.of(2), obj.getTheList());
|
||||
assertTrue(obj.isTheBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void recordHasPrefixedGetters() {
|
||||
var obj = new CustomMethodNames(1, List.of(2), true);
|
||||
assertEquals(1, obj.getTheValue());
|
||||
assertEquals(List.of(2), obj.getTheList());
|
||||
assertTrue(obj.isTheBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noStaticBuilder() {
|
||||
boolean hasStaticBuilder = Stream.of(NoStaticBuilderBuilder.class.getDeclaredMethods())
|
||||
.anyMatch(method -> method.getName().equals("NoStaticBuilder"));
|
||||
assertFalse(hasStaticBuilder);
|
||||
|
||||
hasStaticBuilder = Stream.of(SimpleRecordBuilder.class.getDeclaredMethods())
|
||||
.anyMatch(method -> method.getName().equals("SimpleRecord"));
|
||||
assertTrue(hasStaticBuilder);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
<parent>
|
||||
<groupId>io.soabase.record-builder</groupId>
|
||||
<artifactId>record-builder</artifactId>
|
||||
<version>31</version>
|
||||
<version>34</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user