1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.myfaces.config;
20
21 import java.lang.reflect.InvocationTargetException;
22 import java.util.Map;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
25
26 import javax.faces.component.UIViewRoot;
27 import javax.faces.context.ExternalContext;
28 import javax.faces.context.FacesContext;
29 import javax.faces.event.PreDestroyCustomScopeEvent;
30 import javax.faces.event.PreDestroyViewMapEvent;
31 import javax.faces.event.ScopeContext;
32 import javax.faces.event.SystemEvent;
33 import javax.faces.event.SystemEventListener;
34 import javax.servlet.ServletContext;
35
36 import org.apache.myfaces.config.annotation.LifecycleProvider;
37 import org.apache.myfaces.config.annotation.LifecycleProviderFactory;
38 import org.apache.myfaces.context.servlet.StartupServletExternalContextImpl;
39
40
41
42
43
44
45
46
47 public class ManagedBeanDestroyer implements SystemEventListener
48 {
49
50 private static Logger log = Logger.getLogger(ManagedBeanDestroyer.class.getName());
51
52 private RuntimeConfig _runtimeConfig;
53 private LifecycleProvider _lifecycleProvider;
54
55
56
57
58
59
60
61
62 public ManagedBeanDestroyer(LifecycleProvider lifecycleProvider,
63 RuntimeConfig runtimeConfig)
64 {
65 _lifecycleProvider = lifecycleProvider;
66 _runtimeConfig = runtimeConfig;
67 }
68
69 public boolean isListenerForSource(Object source)
70 {
71
72
73 return (source instanceof ScopeContext) || (source instanceof UIViewRoot);
74 }
75
76
77
78
79
80 public void processEvent(SystemEvent event)
81 {
82 Map<String, Object> scope = null;
83
84 if (event instanceof PreDestroyViewMapEvent)
85 {
86 UIViewRoot viewRoot = (UIViewRoot) ((PreDestroyViewMapEvent) event).getComponent();
87 scope = viewRoot.getViewMap(false);
88 if (scope == null)
89 {
90
91 return;
92 }
93 }
94 else if (event instanceof PreDestroyCustomScopeEvent)
95 {
96 ScopeContext scopeContext = ((PreDestroyCustomScopeEvent) event).getContext();
97 scope = scopeContext.getScope();
98 }
99 else
100 {
101
102 return;
103 }
104
105 for (String key : scope.keySet())
106 {
107 Object value = scope.get(key);
108 this.destroy(key, value);
109 }
110 }
111
112
113
114
115
116
117 public boolean isManagedBean(String name)
118 {
119 return (_runtimeConfig.getManagedBean(name) != null);
120 }
121
122
123
124
125
126
127 public void destroy(String name, Object instance)
128 {
129 if (instance != null && isManagedBean(name))
130 {
131 try
132 {
133 _lifecycleProvider.destroyInstance(instance);
134 }
135 catch (IllegalAccessException e)
136 {
137 log.log(Level.SEVERE, "Could not access @PreDestroy method of managed bean " + name, e);
138 }
139 catch (InvocationTargetException e)
140 {
141 log.log(Level.SEVERE, "An Exception occured while invoking " +
142 "@PreDestroy method of managed bean " + name, e);
143 }
144 }
145 }
146
147 }