All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.redis.riot.faker.FakerItemReader Maven / Gradle / Ivy

There is a newer version: 4.1.3
Show newest version
package com.redis.riot.faker;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

import net.datafaker.Faker;

/**
 * {@link ItemReader} that generates HashMaps using Faker.
 *
 * @author Julien Ruaux
 */
public class FakerItemReader extends AbstractItemCountingItemStreamItemReader> {

	public static final Locale DEFAULT_LOCALE = Locale.getDefault();

	private Map expressions = new LinkedHashMap<>();
	private Locale locale = DEFAULT_LOCALE;

	private Faker faker;
	private Map fields;

	public FakerItemReader() {
		setName(ClassUtils.getShortName(getClass()));
	}

	public void setLocale(Locale locale) {
		this.locale = locale;
	}

	public void setExpressions(Map fields) {
		this.expressions = fields;
	}

	@Override
	protected synchronized void doOpen() throws Exception {
		Assert.notEmpty(expressions, "No field specified");
		if (fields == null) {
			fields = expressions.entrySet().stream().map(this::normalizeField)
					.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
		}
		faker = new Faker(locale);
	}

	private Entry normalizeField(Entry field) {
		if (field.getValue().startsWith("#{")) {
			return field;
		}
		return new AbstractMap.SimpleEntry<>(field.getKey(), "#{" + field.getValue() + "}");
	}

	@Override
	protected Map doRead() throws Exception {
		Map map = new HashMap<>();
		fields.forEach((k, v) -> map.put(k, faker.expression(v)));
		return map;
	}

	@Override
	protected synchronized void doClose() {
		faker = null;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy