001// Copyright 2008-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.AbstractSessionPersistentFieldStrategy;
019import org.hibernate.HibernateException;
020import org.hibernate.Session;
021
022import java.io.Serializable;
023
024/**
025 * Persists Hibernate entities by storing their id in the session.
026 *
027 * @see org.apache.tapestry5.hibernate.web.internal.PersistedEntity
028 */
029public class EntityPersistentFieldStrategy extends AbstractSessionPersistentFieldStrategy
030{
031    private final Session session;
032
033    public EntityPersistentFieldStrategy(Session session, Request request)
034    {
035        super("entity:", request);
036
037        this.session = session;
038    }
039
040    @Override
041    public Object convertApplicationValueToPersisted(Object newValue)
042    {
043        assert newValue != null;
044
045        if (!session.contains(newValue))
046        {
047            return new PersistedTransientEntity(newValue);
048        }
049
050        try
051        {
052            String entityName = session.getEntityName(newValue);
053            Serializable id = session.getIdentifier(newValue);
054
055            return new PersistedEntity(entityName, id);
056        } catch (HibernateException ex)
057        {
058            throw new IllegalArgumentException(String.format("Failed persisting an entity in the session. entity: %s", newValue), ex);
059        }
060    }
061
062    @Override
063    public Object convertPersistedToApplicationValue(Object persistedValue)
064    {
065        assert persistedValue != null;
066
067        SessionRestorable persisted = (SessionRestorable) persistedValue;
068
069        return persisted.restoreWithSession(session);
070    }
071}