01: // Copyright 2007 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // Unless required by applicable law or agreed to in writing, software
10: // distributed under the License is distributed on an "AS IS" BASIS,
11: // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: // See the License for the specific language governing permissions and
13: // limitations under the License.
14:
15: package org.apache.tapestry.internal.services;
16:
17: import org.apache.tapestry.services.ApplicationStateCreator;
18: import org.apache.tapestry.services.ApplicationStatePersistenceStrategy;
19: import org.apache.tapestry.services.Request;
20: import org.apache.tapestry.services.Session;
21:
22: /**
23: * Stores ASOs in the {@link Session}, which will be created as necessary.
24: * <p>
25: * TODO: Re-storing the object back into the session at the end of the request. That's going to
26: * require some kind of end-of-request notification.
27: */
28: public class SessionApplicationStatePersistenceStrategy implements
29: ApplicationStatePersistenceStrategy {
30: static final String PREFIX = "aso:";
31:
32: private final Request _request;
33:
34: public SessionApplicationStatePersistenceStrategy(Request request) {
35: _request = request;
36: }
37:
38: private Session getSession() {
39: return _request.getSession(true);
40: }
41:
42: @SuppressWarnings("unchecked")
43: public <T> T get(Class<T> asoClass,
44: ApplicationStateCreator<T> creator) {
45: Session session = getSession();
46:
47: String key = buildKey(asoClass);
48:
49: T aso = (T) session.getAttribute(key);
50:
51: if (aso == null) {
52: aso = creator.create();
53: session.setAttribute(key, aso);
54: }
55:
56: return aso;
57: }
58:
59: private <T> String buildKey(Class<T> asoClass) {
60: return PREFIX + asoClass.getName();
61: }
62:
63: public <T> void set(Class<T> asoClass, T aso) {
64: String key = buildKey(asoClass);
65:
66: getSession().setAttribute(key, aso);
67: }
68:
69: public <T> boolean exists(Class<T> asoClass) {
70: String key = buildKey(asoClass);
71:
72: Session session = _request.getSession(false);
73:
74: return session != null && session.getAttribute(key) != null;
75: }
76:
77: }
|