001// Copyright 2009, 2014 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.hibernate.web.internal;
016
017import org.apache.tapestry5.http.services.Request;
018import org.apache.tapestry5.internal.services.SessionApplicationStatePersistenceStrategy;
019import org.apache.tapestry5.services.ApplicationStateCreator;
020import org.hibernate.Session;
021
022/**
023 * Persists Hibernate entities as SSOs by storing their primary key in the {@link org.apache.tapestry5.http.services.Session}.
024 *
025 * @see org.apache.tapestry5.hibernate.web.internal.PersistedEntity
026 */
027public class EntityApplicationStatePersistenceStrategy extends SessionApplicationStatePersistenceStrategy
028{
029
030    private final EntityPersistentFieldStrategy delegate;
031
032    public EntityApplicationStatePersistenceStrategy(Request request, Session hibernateSession)
033    {
034        super(request);
035
036        delegate = new EntityPersistentFieldStrategy(hibernateSession, null);
037    }
038
039    @Override
040    @SuppressWarnings("unchecked")
041    public <T> T get(Class<T> ssoClass, ApplicationStateCreator<T> creator)
042    {
043        final Object persistedValue = getOrCreate(ssoClass, creator);
044
045        if (persistedValue instanceof SessionRestorable)
046        {
047            Object restored = delegate.convertPersistedToApplicationValue(persistedValue);
048
049            // Maybe throw an exception instead?
050            if (restored == null)
051            {
052                set(ssoClass, null);
053                return (T) getOrCreate(ssoClass, creator);
054            }
055
056            return (T) restored;
057        }
058
059        return (T) persistedValue;
060    }
061
062    @Override
063    public <T> void set(Class<T> ssoClass, T sso)
064    {
065        final String key = buildKey(ssoClass);
066
067        if (sso == null)
068        {
069            getSession().setAttribute(key, null);
070            return;
071        }
072
073        Object persistable = delegate.convertApplicationValueToPersisted(sso);
074
075        getSession().setAttribute(key, persistable);
076    }
077
078}