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 attributes. The
023 * 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 private WebRequest _request;
031
032 private String _applicationId;
033
034 private String buildKey(String objectName)
035 {
036 // For Portlets, the application id is going to be somewhat redundant, since
037 // the Portlet API keeps portlets seperate anyway.
038
039 return "state:" + _applicationId + ":" + objectName;
040 }
041
042 /**
043 * Returns the session for the current request, creating it if necessary.
044 */
045
046 private WebSession getSession()
047 {
048 return _request.getSession(true);
049 }
050
051 public boolean exists(String objectName)
052 {
053 WebSession session = _request.getSession(false);
054
055 if (session == null)
056 return false;
057
058 return session.getAttribute(buildKey(objectName)) != null;
059 }
060
061 public Object get(String objectName, StateObjectFactory factory)
062 {
063 String key = buildKey(objectName);
064 WebSession session = getSession();
065
066 Object result = session.getAttribute(key);
067 if (result == null)
068 {
069 result = factory.createStateObject();
070 session.setAttribute(key, result);
071 }
072
073 return result;
074 }
075
076 public void store(String objectName, Object stateObject)
077 {
078 if (stateObject instanceof SessionStoreOptimized)
079 {
080 SessionStoreOptimized optimized = (SessionStoreOptimized) stateObject;
081
082 if (!optimized.isStoreToSessionNeeded())
083 return;
084 }
085
086 String key = buildKey(objectName);
087
088 WebSession session = getSession();
089
090 session.setAttribute(key, stateObject);
091 }
092
093 public void setApplicationId(String applicationName)
094 {
095 _applicationId = applicationName;
096 }
097
098 public void setRequest(WebRequest request)
099 {
100 _request = request;
101 }
102 }