SimpleSessionHandler.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.web.concrete;


import net.metanotion.util.Message;

import net.metanotion.web.RequestObject;
import net.metanotion.web.SessionFactory;
import net.metanotion.web.SessionHandler;
import net.metanotion.web.SessionInitializer;
import net.metanotion.web.SessionStore;

/** A simple SessionHandler implementation.
	This SessionHandler caches sessions via an {@link net.metanotion.web.SessionStore}
	implementation. It provides no life cycle management directly and offers no
	option to mangle request responses to aid in recognizing sessions in the future. */
public final class SimpleSessionHandler implements SessionHandler {
	private final SessionInitializer app;

	/** Create a new basic session handler backed by a SessionFactory and a SessionStore.
		This constructor just wraps the pair in a {@link net.metanotion.web.concrete.SimpleSessionInitializer}.
		@param app The application's session factory instance.
		@param store The session store instance/strategy to use.
	*/
	public SimpleSessionHandler(final SessionFactory<RequestObject> app, final SessionStore store) {
		this(new SimpleSessionInitializer(app, store));
	}

	/** Create a new basic session handler backed by a SessionInitializer.
		@param app The application's session initializer instance.
	*/
	public SimpleSessionHandler(final SessionInitializer app) { this.app = app; }

	@Override public Object dispatch(final Message<Object> m, final RequestObject ro) {
		try {
			return m.call(app.getSession(ro).lookupInterface(m.receiverType()));
		} catch (final Exception e) {
			Throwable actual = e;
			while(actual != null) {
				if(actual instanceof HttpException) {
					return ((HttpException) actual).getHttpResponse();
				}
				actual = actual.getCause();
			}
			throw e;
		}
	}
}