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


import net.metanotion.util.Unknown;

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

/** A basic implementation of the SessionInitializer interface that uses a {@link net.metanotion.web.SessionStore}
and {@link net.metanotion.web.SessionFactory} to create and cache sessions.
*/
public final class SimpleSessionInitializer implements SessionInitializer {
	private final SessionStore store;
	private final SessionFactory<RequestObject> app;

	/** Create a SessionInitializer backed by a session store with a session factory representing the application.
		@param app The session factory provided by the application. This will only be used if there is no session
			in the store.
		@param store The session store to cache sessions between requests.
	*/
	public SimpleSessionInitializer(final SessionFactory<RequestObject> app, final SessionStore store) {
		this.store = store;
		this.app = app;
	}

	@Override public Unknown getSession(final RequestObject ro) {
		final Unknown session = store.getSession(ro);
		return (session != null) ? session : store.setSession(ro, app.newSession(ro));
	}
}