Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/documentation/formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ attributes using randomly generated data in the following way:
Collection<Xml.XmlNode> address = faker.<Xml.XmlNode>collection()
.suppliers(() -> new Xml.XmlNode("address",
map(entry("country", faker.address().country()),
entry("city", faker.address().city()), entry("streetAddress", faker.address().streetAddress())), Collections.emptyList()))
entry("city", faker.address().city()), entry("streetAddress", faker.address().streetAddress())), List.of()))
.maxLen(3).build().get();

Collection<Xml.XmlNode> persons = faker.<Xml.XmlNode>collection()
Expand Down
12 changes: 6 additions & 6 deletions docs/documentation/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,13 +271,13 @@ INSERT INTO "MyTable" ("ints") VALUES (ARRAY[1, 2, 3]);
=== "Java"

```java
Schema.of(field("names_multiset", () -> Collections.singleton("hello")));
Schema.of(field("names_multiset", () -> Set.of("hello")));
```

=== "Kotlin"

```kotlin
val schema: Schema<String, Set<String>> = Schema.of(field("names_multiset", Supplier { Collections.singleton("hello") } ))
val schema: Schema<String, Set<String>> = Schema.of(field("names_multiset", Supplier { Set.of("hello") } ))
```

will lead to
Expand Down Expand Up @@ -356,9 +356,9 @@ The following is an example on how to use it:
field("lastname", () -> faker.name().lastName()),
field("phones", () -> Schema.of(
field("worknumbers", () -> ((Stream<?>) faker.<String>stream().suppliers(() -> faker.phoneNumber().phoneNumber()).maxLen(2).build().get())
.collect(Collectors.toList())),
.toList()),
field("cellphones", () -> ((Stream<?>) faker.<String>stream().suppliers(() -> faker.phoneNumber().cellPhone()).maxLen(3).build().get())
.collect(Collectors.toList()))
.toList())
)),
field("address", () -> Schema.of(
field("city", () -> faker.address().city()),
Expand Down Expand Up @@ -549,9 +549,9 @@ The following is an example on how to use it:
field("lastname", () -> faker.name().lastName()),
field("phones", () -> Schema.of(
field("worknumbers", () -> ((Stream<?>) faker.<String>stream().suppliers(() -> faker.phoneNumber().phoneNumber()).maxLen(2).build().get())
.collect(Collectors.toList())),
.toList()),
field("cellphones", () -> ((Stream<?>) faker.<String>stream().suppliers(() -> faker.phoneNumber().cellPhone()).maxLen(3).build().get())
.collect(Collectors.toList()))
.toList())
)),
field("address", () -> Schema.of(
field("city", () -> faker.address().city()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ private PatternType randomType() {
}

private byte[] encodePng(BufferedImage image) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
try (var baos = new ByteArrayOutputStream()) {
ImageIO.write(image, "PNG", baos);
return baos.toByteArray();
} catch (IOException e) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/net/datafaker/providers/base/Image.java
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ private String generateBase64RasterImage(ImageType imageType, int width, int hei
}
graphics.dispose();

try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
try (var baos = new ByteArrayOutputStream()) {
ImageIO.write(bufferedImage, imageType.name(), baos);
byte[] imageBytes = baos.toByteArray();
return "data:" + imageType.mimeType + ";base64," + Base64.getEncoder().encodeToString(imageBytes);
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/net/datafaker/providers/base/Internet.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import java.nio.ByteBuffer;
import java.text.Normalizer;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -135,7 +134,7 @@ private String toLocalPart(String name) {
final List<String> prefixList = (prefixObj instanceof List<?> list
&& list.stream().allMatch(String.class::isInstance))
? list.stream().map(String.class::cast).toList()
: Collections.emptyList();
: List.of();
if (prefixList.contains(parts[0])) {
parts = Arrays.copyOfRange(parts, 1, parts.length);
}
Expand All @@ -144,7 +143,7 @@ private String toLocalPart(String name) {
final List<String> suffixList = (suffixObj instanceof List<?> list
&& list.stream().allMatch(String.class::isInstance))
? list.stream().map(String.class::cast).toList()
: Collections.emptyList();
: List.of();
if (suffixList.contains(parts[parts.length - 1])) {
parts = Arrays.copyOfRange(parts, 0, parts.length - 1);
}
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/net/datafaker/providers/base/Options.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package net.datafaker.providers.base;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
Expand Down Expand Up @@ -76,7 +75,7 @@ public final <E> Set<E> subset(int size, E... options) {
throw new IllegalArgumentException("size should be not negative: " + size);
}
if (size == 0) {
return Collections.emptySet();
return Set.of();
}
List<E> opts = Stream.of(options).distinct().collect(Collectors.toList());
if (size >= opts.size()) {
Expand Down Expand Up @@ -119,7 +118,7 @@ public final Set<String> subset(int size, String... options) {
throw new IllegalArgumentException("size should be not negative: " + size);
}
if (size == 0) {
return Collections.emptySet();
return Set.of();
}
List<String> opts = Stream.of(options).distinct().collect(Collectors.toList());
if (size >= opts.size()) {
Expand Down
17 changes: 8 additions & 9 deletions src/main/java/net/datafaker/service/FakeValues.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static java.util.Collections.emptyMap;
import static net.datafaker.internal.helper.JavaNames.toJavaNames;

public class FakeValues implements FakeValuesInterface {
Expand All @@ -41,7 +40,7 @@ private Map<String, Object> loadFromUrl() {
if (url == null) {
return null;
}
try (InputStream stream = url.openStream()) {
try (var stream = url.openStream()) {
Map<String, Object> result = readFromStream(stream);
enrichMapWithJavaNames(result);
return result;
Expand All @@ -64,12 +63,12 @@ private Map<String, Object> loadValues() {
"/" + locale.getLanguage() + ".yml"};

for (String path : paths) {
try (InputStream stream = getClass().getResourceAsStream(path)) {
try (var stream = getClass().getResourceAsStream(path)) {
if (stream != null) {
result = readFromStream(stream);
enrichMapWithJavaNames(result);
} else {
try (InputStream stream2 = getClass().getClassLoader().getResourceAsStream(path)) {
try (var stream2 = getClass().getClassLoader().getResourceAsStream(path)) {
result = readFromStream(stream2);
enrichMapWithJavaNames(result);
}
Expand All @@ -82,21 +81,21 @@ private Map<String, Object> loadValues() {
return result;
}
}
return emptyMap();
return Map.of();
}

private void enrichMapWithJavaNames(Map<String, Object> result) {
if (result != null) {
Map<String, Object> map = null;
for (Map.Entry<String, Object> entry : result.entrySet()) {
for (var entry : result.entrySet()) {
final String key = entry.getKey();
Object value = entry.getValue();
if (entry.getValue() instanceof Map) {
if (value instanceof Map<?, ?> rawMap) {
@SuppressWarnings("unchecked")
Map<String, Object> entryMap = (Map<String, Object>) entry.getValue();
Map<String, Object> entryMap = (Map<String, Object>) rawMap;
prefixUnqualifiedExpressions(entryMap, key);
Map<String, Object> nestedMap = new HashMap<>(entryMap.size());
for (Map.Entry<String, Object> e: entryMap.entrySet()) {
for (var e : entryMap.entrySet()) {
nestedMap.put(toJavaNames(e.getKey(), true), e.getValue());
}
entryMap.putAll(nestedMap);
Expand Down
12 changes: 6 additions & 6 deletions src/main/java/net/datafaker/service/FakeValuesGrouping.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import net.datafaker.service.files.EnFile;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;

Expand All @@ -27,12 +27,12 @@ public FakeValuesGrouping(FakeValues values) {
}

public void add(FakeValuesInterface fakeValue) {
if (fakeValue instanceof FakeValues) {
((FakeValues) fakeValue).getPaths().forEach(p ->
if (fakeValue instanceof FakeValues values) {
values.getPaths().forEach(p ->
fakeValues.computeIfAbsent(p, key -> new HashSet<>())
.add(fakeValue));
} else if (fakeValue instanceof FakeValuesGrouping) {
fakeValues.putAll(((FakeValuesGrouping) fakeValue).fakeValues);
} else if (fakeValue instanceof FakeValuesGrouping grouping) {
fakeValues.putAll(grouping.fakeValues);
} else {
throw new RuntimeException(fakeValues.getClass().getName() + " not supported (please raise an issue)");
}
Expand All @@ -42,7 +42,7 @@ public void add(FakeValuesInterface fakeValue) {
@SuppressWarnings({"unchecked", "rawtypes"})
public Map get(String key) {
Map result = null;
for (FakeValuesInterface fakeValues : fakeValues.getOrDefault(key, Collections.emptyList())) {
for (FakeValuesInterface fakeValues : fakeValues.getOrDefault(key, List.of())) {
if (result == null) {
result = fakeValues.get(key);
} else {
Expand Down
56 changes: 21 additions & 35 deletions src/main/java/net/datafaker/service/FakeValuesService.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import java.util.Collection;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
Expand All @@ -42,8 +41,6 @@
import java.util.logging.Logger;
import java.util.stream.Collectors;

import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static java.util.Locale.ROOT;
import static java.util.Objects.requireNonNull;
import static java.util.logging.Level.FINE;
Expand Down Expand Up @@ -144,8 +141,8 @@ public void addUrl(Locale locale, URL url) {
public Object fetch(String key, FakerContext context) {
List<?> valuesArray = null;
final Object o = fetchObject(key, context);
if (o instanceof List) {
valuesArray = (List<?>) o;
if (o instanceof List<?> list) {
valuesArray = list;
final int size = valuesArray.size();
if (size == 0) {
return null;
Expand All @@ -165,23 +162,12 @@ public String fetchString(String key, FakerContext context) {
return (String) fetch(key, context);
}

private class SafeFetchResolver implements ValueResolver {
private final String simpleDirective;
private final FakerContext context;

private SafeFetchResolver(String simpleDirective, FakerContext context) {
this.simpleDirective = simpleDirective;
this.context = context;
}
private record SafeFetchResolver(FakeValuesService service, String simpleDirective, FakerContext context)
implements ValueResolver {

@Override
public Object resolve() {
return safeFetch(simpleDirective, context, null);
}

@Override
public String toString() {
return "%s[simpleDirective=%s, context=%s]".formatted(getClass().getSimpleName(), simpleDirective, context);
return service.safeFetch(simpleDirective, context, null);
}
}

Expand All @@ -206,8 +192,8 @@ public String safeFetch(String key, FakerContext context, String defaultIfNull)
Object o = fetchObject(key, context);
String str;
if (o == null) return defaultIfNull;
if (o instanceof List) {
final List<String> values = (List<String>) o;
if (o instanceof List<?> list) {
final List<String> values = (List<String>) list;
final int size = values.size();
return switch (size) {
case 0 -> defaultIfNull;
Expand Down Expand Up @@ -250,8 +236,8 @@ public <T> T fetchObject(String key, FakerContext context) {
Object currentValue = fakeValuesInterfaceMap.get(sLocale);
for (int p = 0; currentValue != null && p < path.length; p++) {
String currentPath = path[p];
if (currentValue instanceof Map) {
currentValue = ((Map<?, ?>) currentValue).get(currentPath);
if (currentValue instanceof Map<?, ?> map) {
currentValue = map.get(currentPath);
} else {
currentValue = ((FakeValuesInterface) currentValue).get(currentPath);
}
Expand All @@ -264,7 +250,7 @@ public <T> T fetchObject(String key, FakerContext context) {
}
if (local2Add != null) {
Object valueToCache = result;
Object curResult = key2fetchedObject.getOrDefault(local2Add, emptyMap()).get(key);
Object curResult = key2fetchedObject.getOrDefault(local2Add, Map.of()).get(key);
if (curResult != null) {
return (T) result; // Strange... Why return result, not curResult?
}
Expand Down Expand Up @@ -683,14 +669,14 @@ private String[] splitExpressions(String expression, int length) {
private Object resExp(String directive, String[] args, Object current, ProviderRegistration root, FakerContext context, String expr) {
Object res = resolveExpression(directive, args, current, root, context);
LOG.fine(() -> "resExp(%s [%s]) current: %s, root: %s, context: %s, expr: %s -> res: %s".formatted(directive, Arrays.toString(args), current, root, context, expr, res));
if (res instanceof CharSequence) {
if (((CharSequence) res).isEmpty()) {
if (res instanceof CharSequence charSequence) {
if (charSequence.isEmpty()) {
regexp2SupplierMap.put(expr, new RegExpContext(root, context, EMPTY_STRING));
}
return res;
}
if (res instanceof List) {
Iterator<ValueResolver> it = ((List<ValueResolver>) res).iterator();
if (res instanceof List<?> list) {
var it = ((List<ValueResolver>) list).iterator();
while (it.hasNext()) {
Object valueResolver = it.next();
Object value;
Expand Down Expand Up @@ -729,8 +715,8 @@ private Object resolveExpression(String directive, String[] args, Object current
// resolve method references on CURRENT object like #{number_between '1','10'} on Number or
// #{ssn_valid} on IdNumber
if (dotIndex == -1) {
if (current instanceof AbstractProvider) {
final Method method = BaseFaker.getMethod((AbstractProvider<?>) current, directive);
if (current instanceof AbstractProvider<?> provider) {
final Method method = BaseFaker.getMethod(provider, directive);
if (method != null) {
res.add(new MethodResolver(method, current, args));
return res;
Expand All @@ -757,7 +743,7 @@ private Object resolveExpression(String directive, String[] args, Object current
// car.wheel will be looked up in the YAML file.
// It's only "simple" if there aren't args
if (args.length == 0) {
res.add(new SafeFetchResolver(simpleDirective, context));
res.add(new SafeFetchResolver(this, simpleDirective, context));
}

// resolve method references on faker object like #{regexify '[a-z]'}
Expand All @@ -777,7 +763,7 @@ private Object resolveExpression(String directive, String[] args, Object current
// class.method_name (lowercase)
if (dotIndex >= 0) {
final String key = javaNameToYamlName(simpleDirective);
res.add(new SafeFetchResolver(key, context));
res.add(new SafeFetchResolver(this, key, context));
}

return res;
Expand Down Expand Up @@ -922,10 +908,10 @@ private MethodAndCoercedArgs accessor(Class<?> clazz, final String accessorName,
LOG.fine(() -> "Find accessor named %s on %s with args %s".formatted(accessorName, clazz.getSimpleName(), Arrays.toString(args)));
String name = removeUnderscoreChars(accessorName);

Map<String, Collection<Method>> classMethodsMap = CLASS_2_METHODS_CACHE.computeIfAbsent(clazz, (__) -> {
var classMethodsMap = CLASS_2_METHODS_CACHE.computeIfAbsent(clazz, (__) -> {
Method[] classMethods = clazz.getMethods();
Map<String, Collection<Method>> methodMap =
classMethods.length == 0 ? emptyMap() : new HashMap<>(classMethods.length);
classMethods.length == 0 ? Map.of() : new HashMap<>(classMethods.length);
for (Method m : classMethods) {
String key = m.getName().toLowerCase(ROOT);
methodMap.computeIfAbsent(key, k -> new ArrayList<>()).add(m);
Expand All @@ -934,7 +920,7 @@ private MethodAndCoercedArgs accessor(Class<?> clazz, final String accessorName,
return methodMap;
});

Collection<Method> methods = classMethodsMap.getOrDefault(name, emptyList());
Collection<Method> methods = classMethodsMap.getOrDefault(name, List.of());
if (methods.isEmpty()) {
LOG.fine(() -> "Didn't find accessor named %s on %s with args %s".formatted(accessorName, clazz.getSimpleName(), Arrays.toString(args)));
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

import net.datafaker.sequence.FakeSequence;

import java.util.Iterator;

public class CsvTransformer<IN> implements Transformer<IN, CharSequence> {
public static final String DEFAULT_SEPARATOR = ";";
public static final char DEFAULT_QUOTE = '"';
Expand Down Expand Up @@ -46,7 +44,7 @@ public String generate(Iterable<IN> input, Schema<IN, ?> schema) {
StringBuilder sb = new StringBuilder();
generateHeader(schema, sb, true);

Iterator<IN> iterator = input.iterator();
var iterator = input.iterator();
boolean hasNext = iterator.hasNext();
while (hasNext) {
IN in = iterator.next();
Expand All @@ -61,8 +59,8 @@ public String generate(Iterable<IN> input, Schema<IN, ?> schema) {
}

private void addLine(StringBuilder sb, Object transform) {
if (transform instanceof CharSequence) {
addCharSequence(sb, (CharSequence) transform);
if (transform instanceof CharSequence charSequence) {
addCharSequence(sb, charSequence);
} else {
sb.append(transform);
}
Expand Down
Loading
Loading