001 // Copyright 2005 The Apache Software Foundation
002 //
003 // Licensed under the Apache License, Version 2.0 (the "License");
004 // you may not use this file except in compliance with the License.
005 // You may obtain a copy of the License at
006 //
007 // http://www.apache.org/licenses/LICENSE-2.0
008 //
009 // Unless required by applicable law or agreed to in writing, software
010 // distributed under the License is distributed on an "AS IS" BASIS,
011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 // See the License for the specific language governing permissions and
013 // limitations under the License.
014
015 package org.apache.tapestry.engine.state;
016
017 import org.apache.tapestry.SessionStoreOptimized;
018 import org.apache.tapestry.web.WebRequest;
019 import org.apache.tapestry.web.WebSession;
020
021 /**
022 * Manager for the 'session' scope; state objects are stored as HttpSession
023 * attributes. The HttpSession is created as necessary.
024 *
025 * @author Howard M. Lewis Ship
026 * @since 4.0
027 */
028 public class SessionScopeManager implements StateObjectPersistenceManager
029 {
030
031 private WebRequest _request;
032
033 private String _applicationId;
034
035 private String buildKey(String objectName)
036 {
037 // For Portlets, the application id is going to be somewhat redundant,
038 // since
039 // the Portlet API keeps portlets seperate anyway.
040
041 return "state:" + _applicationId + ":" + objectName;
042 }
043
044 /**
045 * Returns the session for the current request, creating it if necessary.
046 */
047
048 private WebSession getSession()
049 {
050 return _request.getSession(true);
051 }
052
053 public boolean exists(String objectName)
054 {
055 WebSession session = _request.getSession(false);
056
057 if (session == null) return false;
058
059 return session.getAttribute(buildKey(objectName)) != null;
060 }
061
062 public Object get(String objectName, StateObjectFactory factory)
063 {
064 String key = buildKey(objectName);
065 WebSession session = getSession();
066
067 Object result = session.getAttribute(key);
068 if (result == null)
069 {
070 result = factory.createStateObject();
071 session.setAttribute(key, result);
072 }
073
074 return result;
075 }
076
077 public void store(String objectName, Object stateObject)
078 {
079 if (stateObject instanceof SessionStoreOptimized)
080 {
081 SessionStoreOptimized optimized = (SessionStoreOptimized) stateObject;
082
083 if (!optimized.isStoreToSessionNeeded())
084 return;
085 }
086
087 String key = buildKey(objectName);
088
089 WebSession session = getSession();
090
091 session.setAttribute(key, stateObject);
092 }
093
094 public void setApplicationId(String applicationName)
095 {
096 _applicationId = applicationName;
097 }
098
099 public void setRequest(WebRequest request)
100 {
101 _request = request;
102 }
103 }