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

prompto.store.datomic.DatomicFacts Maven / Gradle / Ivy

There is a newer version: 0.0.136
Show newest version
package prompto.store.datomic;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;

public class DatomicFacts {

	Object dbId;
	Map toAdd = new HashMap<>();
	
	public DatomicFacts(Object dbId) {
		this.dbId = dbId;
	}

	public Object getDbId() {
		return dbId;
	}
	
	public void setDbId(Object dbId) {
		this.dbId = dbId;
	}
	
	public void add(String name, Object value) {
		toAdd.put(":" + name, value);
	}

	public Stream> getAddedFacts() {
		Stream> singles = getSingleValueFacts();
		Stream> multiples = getMultiValueFacts();
		return Stream.concat(singles, multiples);
	}

	@SuppressWarnings("unchecked")
	private Stream> getMultiValueFacts() {
		return toAdd.entrySet().stream()
				.filter(e->e.getValue() instanceof Collection)
				.map(e->getMultiValueFacts(e.getKey(), (Collection)e.getValue()))
				.flatMap(Function.identity());

	}
	
	private Stream> getMultiValueFacts(Object key, Collection values) {
		return values.stream().map(v->Arrays.asList(":db/add", dbId, key, v));
	}

	private Stream> getSingleValueFacts() {
		return toAdd.entrySet().stream()
			.filter(e->!(e.getValue() instanceof Collection))
			.map(e->Arrays.asList(":db/add", dbId, e.getKey(), e.getValue()));
	}
	
	
}