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

com.xlrit.gears.engine.snel.EvaluatorScope Maven / Gradle / Ivy

package com.xlrit.gears.engine.snel;

import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.xlrit.gears.engine.meta.BaseField;
import com.xlrit.gears.engine.meta.EntityInfo;
import com.xlrit.gears.engine.meta.MultipleInfo;
import lombok.RequiredArgsConstructor;

public interface EvaluatorScope {

	Result getValue(String name);

	EvaluatorScope ROOT = new RootScope();

	static EvaluatorScope forValues(Map values) {
		return new ValueScope(ROOT, values);
	}

	static EvaluatorScope forEntity(EntityInfo entityInfo, Object obj) {
		return new EntityScope(ROOT, entityInfo, obj);
	}

	static EvaluatorScope forEntities(Collection> entityInfos) {
		return new EntityCollectionScope(ROOT, entityInfos);
	}

	class RootScope implements EvaluatorScope {
		@Override
		public Result getValue(String name) {
			throw new EvaluatorException("No value for '" + name + "'");
		}
	}

	@RequiredArgsConstructor
	abstract class SubScope implements EvaluatorScope {
		private final EvaluatorScope parent;

		@Override
		public Result getValue(String name) {
			return parent.getValue(name);
		}
	}

	class ValueScope extends SubScope {
		private final Map values;

		public ValueScope(EvaluatorScope parent, Map values) {
			super(parent);
			this.values = values;
		}

		@Override
		public Result getValue(String name) {
			Result value = values.get(name);
			if (value != null) {
				return value;
			}
			return super.getValue(name);
		}
	}

	class EntityScope extends SubScope {
		private final EntityInfo entityInfo;
		private final Object instance;

		public EntityScope(EvaluatorScope parent, EntityInfo entityInfo, Object instance) {
			super(parent);
			this.entityInfo = entityInfo;
			this.instance = instance;
		}

		@Override
		public Result getValue(String name) {
			if ("this".equals(name)) {
				return Result.typed(entityInfo, instance);
			}
			BaseField field = entityInfo.getField(name);
			Object value = field.getValue(instance);
			return Result.typed(field.getTypeInfo(), value);
		}
	}

	class EntityCollectionScope extends SubScope {
		private final Map> entityCollections;

		public EntityCollectionScope(EvaluatorScope parent, Collection> entityInfos) {
			super(parent);
			this.entityCollections = entityInfos.stream().collect(Collectors.toMap(EntityInfo::getCollectionName, Function.identity()));
		}

		@Override
		public Result getValue(String name) {
			EntityInfo entityInfo = entityCollections.get(name);
			if (entityInfo != null) {
				MultipleInfo.OfList collectionType = new MultipleInfo.OfList(entityInfo);
				return Result.typed(collectionType, entityInfo.getRepository().findAll());
			}
			return super.getValue(name);
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy