001 // Copyright 2011 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.tapestry5.internal.jpa; 016 017 import org.apache.tapestry5.internal.services.SessionApplicationStatePersistenceStrategy; 018 import org.apache.tapestry5.jpa.EntityManagerManager; 019 import org.apache.tapestry5.services.ApplicationStateCreator; 020 import org.apache.tapestry5.services.Request; 021 022 public class EntityApplicationStatePersistenceStrategy extends 023 SessionApplicationStatePersistenceStrategy 024 { 025 private final EntityManagerManager entityManagerManager; 026 027 public EntityApplicationStatePersistenceStrategy(final Request request, 028 final EntityManagerManager entityManagerManager) 029 { 030 super(request); 031 032 this.entityManagerManager = entityManagerManager; 033 } 034 035 @Override 036 public <T> T get(final Class<T> ssoClass, final ApplicationStateCreator<T> creator) 037 { 038 final Object persistedValue = getOrCreate(ssoClass, creator); 039 040 if (persistedValue instanceof PersistedEntity) 041 { 042 final PersistedEntity persisted = (PersistedEntity) persistedValue; 043 044 final Object restored = persisted.restore(entityManagerManager); 045 046 // shall we maybe throw an exception instead? 047 if (restored == null) 048 { 049 set(ssoClass, null); 050 return (T) getOrCreate(ssoClass, creator); 051 } 052 053 return (T) restored; 054 } 055 056 return (T) persistedValue; 057 } 058 059 @Override 060 public <T> void set(final Class<T> ssoClass, final T sso) 061 { 062 final String key = buildKey(ssoClass); 063 064 Object entity; 065 066 if (sso != null) 067 { 068 try 069 { 070 entity = JpaInternalUtils.convertApplicationValueToPersisted(entityManagerManager, 071 sso); 072 } 073 catch (final RuntimeException ex) 074 { 075 // if entity not attached to an EntityManager yet, store it as usual sso 076 entity = sso; 077 } 078 } 079 else 080 { 081 entity = sso; 082 } 083 084 getSession().setAttribute(key, entity); 085 } 086 087 }