ResourceDispatcher.java

/***************************************************************************
   Copyright 2013 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.simpletemplate;


import net.metanotion.scripting.ObjectServer;
import net.metanotion.util.Dispatcher;
import net.metanotion.util.Message;
import net.metanotion.util.Unknown;
import net.metanotion.web.RequestObject;

/** The main dispatcher to associate with the template engine.
This dispatcher assumes that the ObjectServer and ResourceFactory associated with a request will be
available from the session object as services. */
public final class ResourceDispatcher implements Dispatcher<Unknown,RequestObject> {
	private final String prefix;

	/** Create a resource dispatcher with no path prefix. */
	public ResourceDispatcher() { this(""); }

	/** Create a new resource dispatcher that translates request object resources into resource factory lookups
	that are then evaluated and the results of the resource evaluation are returned as the result of the request.
		@param pathPrefix The prefix to add to all resource requests.
	*/
	public ResourceDispatcher(String pathPrefix) { this.prefix = pathPrefix; }

	private static final class Msg implements Message<Unknown> {
		private final String prefix;
		private final RequestObject ro;
		public Msg(final String prefix, final RequestObject ro) {
			this.prefix = prefix;
			this.ro = ro;
		}

		@Override public Class<Unknown> receiverType() { return Unknown.class; }
		@Override public Object call(final Unknown o) {
			final ResourceFactory rf = o.lookupInterface(ResourceFactory.class);
			final ObjectServer os = o.lookupInterface(ObjectServer.class);
			return rf.get(this.prefix + ro.getResource()).skin(os,ro);
		}
	}

	@Override public Message<Unknown> dispatch(final RequestObject ro) { return new Msg(prefix, ro); }
}