/* * Copyright 2005 the original author or authors. * * 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 org.wamblee.photos.servlet; import java.security.SecureRandom; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.wamblee.cache.Cache; import org.wamblee.general.BeanKernel; import org.wamblee.photos.model.Album; import org.wamblee.photos.model.authorization.AuthorizedAlbum; import org.wamblee.security.authorization.AuthorizationService; /** * Wrapper class for a session that provides a type-safe interface to the * session for the photos application. */ public class PhotoSession { private static final Logger LOGGER = Logger.getLogger(PhotoSession.class); /** * Attribute key for the photo album in the session. */ private static final String ALBUM_KEY = "album"; /** * Http session. */ private HttpSession _session; /** * Constructs the wrapper. * * @param aSession * Session. */ public PhotoSession(HttpSession aSession) { _session = aSession; } /** * Retrieves the album from the session. * * @return Photo album. */ public Album getAlbum() { return (Album) _session.getAttribute(ALBUM_KEY); } /** * Performs session initialization. * * @param aAlbum * Configured photo album. */ public void sessionCreated() { LOGGER.info("Initializing album with authorized entries"); // NOTE: In some circumstances the container reuses the session id for the next // session it creates, so we have to make it unique by adding a random number // to the end. _session.setAttribute(ALBUM_KEY, new AuthorizedAlbum( getConfiguredAlbum(), getAuthorizationService(), BeanKernel .getBeanFactory().find("authorizedPhotoCache", Cache.class), _session.getId() + "/" + new SecureRandom().nextInt())); } /** * Performs session cleanup. */ public void sessionDestroyed() { LOGGER.info("Unsubscribing the authorized album"); _session.removeAttribute(ALBUM_KEY); } /** * Prepares the session for passivation. * */ public void sessionWillPassivate() { sessionDestroyed(); } /** * Initializes the session after activation. * */ public void sessionDidActivate() { sessionCreated(); } /** * Gets the configured photo album. * * @return Album to use. */ private Album getConfiguredAlbum() { return BeanKernel.getBeanFactory().find(Album.class); } /** * Gets the authorization service. * * @return Authorization service. */ private AuthorizationService getAuthorizationService() { return BeanKernel.getBeanFactory().find(AuthorizationService.class); } }