001// Copyright 2007, 2008, 2009, 2010 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
015package org.apache.tapestry5.internal.services;
016
017import org.apache.tapestry5.services.ApplicationStateCreator;
018import org.apache.tapestry5.services.ApplicationStatePersistenceStrategy;
019import org.apache.tapestry5.services.Request;
020import org.apache.tapestry5.services.Session;
021
022/**
023 * Stores ASOs in the {@link Session}, which will be created as necessary.
024 */
025public class SessionApplicationStatePersistenceStrategy implements ApplicationStatePersistenceStrategy
026{
027    static final String PREFIX = "sso:";
028
029    private final Request request;
030
031    public SessionApplicationStatePersistenceStrategy(Request request)
032    {
033        this.request = request;
034    }
035
036    protected Session getSession()
037    {
038        return request.getSession(true);
039    }
040
041    @SuppressWarnings("unchecked")
042    public <T> T get(Class<T> ssoClass, ApplicationStateCreator<T> creator)
043    {
044        return (T) getOrCreate(ssoClass, creator);
045    }
046    
047    protected <T> Object getOrCreate(Class<T> ssoClass, ApplicationStateCreator<T> creator)
048    {
049        Session session = getSession();
050
051        String key = buildKey(ssoClass);
052
053        Object sso = session.getAttribute(key);
054
055        if (sso == null)
056        {
057            sso = creator.create();
058            set(ssoClass, (T) sso);
059        }
060
061        return sso;
062    }
063
064    protected <T> String buildKey(Class<T> ssoClass)
065    {
066        return PREFIX + ssoClass.getName();
067    }
068
069    public <T> void set(Class<T> ssoClass, T sso)
070    {
071        String key = buildKey(ssoClass);
072
073        getSession().setAttribute(key, sso);
074    }
075
076    public <T> boolean exists(Class<T> ssoClass)
077    {
078        Session session = request.getSession(false);
079
080        return session != null && session.getAttribute(buildKey(ssoClass)) != null;
081    }
082}