001    // Copyright 2007, 2008 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.services;
016    
017    import static org.apache.tapestry5.ioc.internal.util.CollectionFactory.newList;
018    import static org.apache.tapestry5.ioc.internal.util.Defense.notBlank;
019    import org.apache.tapestry5.services.PersistentFieldChange;
020    import org.apache.tapestry5.services.PersistentFieldStrategy;
021    import org.apache.tapestry5.services.Request;
022    import org.apache.tapestry5.services.Session;
023    
024    import java.util.Collection;
025    import java.util.Collections;
026    import java.util.List;
027    
028    /**
029     * Base class for strategies that store their values as keys in the session. Implements a uniform format for the keys,
030     * based on a prefix to identify the particular strategy.
031     */
032    public abstract class AbstractSessionPersistentFieldStrategy implements PersistentFieldStrategy
033    {
034        private final String prefix;
035    
036        private final Request request;
037    
038        protected AbstractSessionPersistentFieldStrategy(String prefix, Request request)
039        {
040            this.prefix = prefix;
041            this.request = request;
042        }
043    
044        public final Collection<PersistentFieldChange> gatherFieldChanges(String pageName)
045        {
046            Session session = request.getSession(false);
047    
048            if (session == null) return Collections.emptyList();
049    
050            List<PersistentFieldChange> result = newList();
051    
052            String fullPrefix = prefix + pageName + ":";
053    
054            for (String name : session.getAttributeNames(fullPrefix))
055            {
056                Object persistedValue = session.getAttribute(name);
057    
058                Object applicationValue = persistedValue == null ? null : convertPersistedToApplicationValue(
059                        persistedValue);
060    
061                PersistentFieldChange change = buildChange(name, applicationValue);
062    
063                result.add(change);
064    
065                didReadChange(session, name);
066            }
067    
068            return result;
069        }
070    
071        public void discardChanges(String pageName)
072        {
073            Session session = request.getSession(false);
074    
075            if (session == null) return;
076    
077            String fullPrefix = prefix + pageName + ":";
078    
079            for (String name : session.getAttributeNames(fullPrefix))
080            {
081                session.setAttribute(name, null);
082            }
083        }
084    
085        /**
086         * Called after each key is read by {@link #gatherFieldChanges(String)}. This implementation does nothing,
087         * subclasses may override.
088         *
089         * @param session       the session from which a value was just read
090         * @param attributeName the name of the attribute used to read a value
091         */
092        protected void didReadChange(Session session, String attributeName)
093        {
094        }
095    
096        private PersistentFieldChange buildChange(String name, Object newValue)
097        {
098            String[] chunks = name.split(":");
099    
100            // Will be empty string for the root component
101            String componentId = chunks[2];
102            String fieldName = chunks[3];
103    
104            return new PersistentFieldChangeImpl(componentId, fieldName, newValue);
105        }
106    
107        public final void postChange(String pageName, String componentId, String fieldName,
108                                     Object newValue)
109        {
110            notBlank(pageName, "pageName");
111            notBlank(fieldName, "fieldName");
112    
113            Object persistedValue = newValue == null ? null : convertApplicationValueToPersisted(newValue);
114    
115            StringBuilder builder = new StringBuilder(prefix);
116            builder.append(pageName);
117            builder.append(':');
118    
119            if (componentId != null) builder.append(componentId);
120    
121            builder.append(':');
122            builder.append(fieldName);
123    
124            Session session = request.getSession(persistedValue != null);
125    
126            // TAPESTRY-2308: The session will be false when newValue is null and the session
127            // does not already exist.
128    
129            if (session != null)
130            {
131                session.setAttribute(builder.toString(), persistedValue);
132            }
133        }
134    
135        /**
136         * Hook that allows a value to be converted as it is written to the session. Passed the new value provided by the
137         * application, returns the object to be stored in the session. This implementation simply returns the provided
138         * value.
139         *
140         * @param newValue non-null value
141         * @return persisted value
142         * @see #convertPersistedToApplicationValue(Object)
143         */
144        protected Object convertApplicationValueToPersisted(Object newValue)
145        {
146            return newValue;
147        }
148    
149        /**
150         * Converts a persisted value stored in the session back into an application value.   This implementation returns
151         * the persisted value as is.
152         *
153         * @param persistedValue non-null persisted value
154         * @return application value
155         * @see #convertPersistedToApplicationValue(Object)
156         */
157        protected Object convertPersistedToApplicationValue(Object persistedValue)
158        {
159            return persistedValue;
160        }
161    }