DictionaryServer.java

/***************************************************************************
   Copyright 2012 Emily Estes

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
***************************************************************************/
package net.metanotion.scripting;


import java.util.Map;

import net.metanotion.util.Dictionary;
import net.metanotion.util.Dispatcher;
import net.metanotion.util.Message;
import net.metanotion.util.Pair;

/** An ObjectServer implementation backed by two dictionary instances.
One dictionary provides the dispatchers, the other provides object instances.
*/
public final class DictionaryServer implements ObjectServer {
	private final Dispatcher<? extends Object,Map.Entry<String,? extends Object>> dispatchers;
	private final Dictionary<String,Object> objects;

	/** Create an ObjectServer backed by two dictionaries for lookups.
		@param dispatchers The dictionary to perform dispatcher lookups on.
		@param objects The dictionary to perform object lookups on.
	*/
	public DictionaryServer(Dispatcher<? extends Object,Map.Entry<String,? extends Object>> dispatchers,
				Dictionary<String,Object> objects) {
		this.dispatchers = dispatchers;
		this.objects = objects;
	}

	@Override public Dispatcher dispatcher(final String name) {
		return new Dispatcher() {
			@Override public Message dispatch(Object data) {
				return dispatchers.dispatch(new Pair<String,Object>(name, data));
			}
		};
	}

	@Override public Object get(String name) { return objects.get(name); }
}