|
| 1 | +package com.redis.riot.faker; |
| 2 | + |
| 3 | +import java.util.AbstractMap; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.LinkedHashMap; |
| 6 | +import java.util.Locale; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.Map.Entry; |
| 9 | +import java.util.stream.Collectors; |
| 10 | + |
| 11 | +import org.springframework.batch.item.ItemReader; |
| 12 | +import org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader; |
| 13 | +import org.springframework.util.Assert; |
| 14 | +import org.springframework.util.ClassUtils; |
| 15 | + |
| 16 | +import net.datafaker.Faker; |
| 17 | + |
| 18 | +/** |
| 19 | + * {@link ItemReader} that generates HashMaps using Faker. |
| 20 | + * |
| 21 | + * @author Julien Ruaux |
| 22 | + */ |
| 23 | +public class FakerItemReader extends AbstractItemCountingItemStreamItemReader<Map<String, Object>> { |
| 24 | + |
| 25 | + public static final Locale DEFAULT_LOCALE = Locale.getDefault(); |
| 26 | + |
| 27 | + private Map<String, String> expressions = new LinkedHashMap<>(); |
| 28 | + private Locale locale = DEFAULT_LOCALE; |
| 29 | + |
| 30 | + private Faker faker; |
| 31 | + private Map<String, String> fields; |
| 32 | + |
| 33 | + public FakerItemReader() { |
| 34 | + setName(ClassUtils.getShortName(getClass())); |
| 35 | + } |
| 36 | + |
| 37 | + public void setLocale(Locale locale) { |
| 38 | + this.locale = locale; |
| 39 | + } |
| 40 | + |
| 41 | + public void setExpressions(Map<String, String> fields) { |
| 42 | + this.expressions = fields; |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + protected synchronized void doOpen() throws Exception { |
| 47 | + Assert.notEmpty(expressions, "No field specified"); |
| 48 | + if (fields == null) { |
| 49 | + fields = expressions.entrySet().stream().map(this::normalizeField) |
| 50 | + .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); |
| 51 | + } |
| 52 | + faker = new Faker(locale); |
| 53 | + } |
| 54 | + |
| 55 | + private Entry<String, String> normalizeField(Entry<String, String> field) { |
| 56 | + if (field.getValue().startsWith("#{")) { |
| 57 | + return field; |
| 58 | + } |
| 59 | + return new AbstractMap.SimpleEntry<>(field.getKey(), "#{" + field.getValue() + "}"); |
| 60 | + } |
| 61 | + |
| 62 | + @Override |
| 63 | + protected Map<String, Object> doRead() throws Exception { |
| 64 | + Map<String, Object> map = new HashMap<>(); |
| 65 | + fields.forEach((k, v) -> map.put(k, faker.expression(v))); |
| 66 | + return map; |
| 67 | + } |
| 68 | + |
| 69 | + @Override |
| 70 | + protected synchronized void doClose() { |
| 71 | + faker = null; |
| 72 | + } |
| 73 | + |
| 74 | +} |
0 commit comments