1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package com.fatwire.gst.foundation.controller.support;
17
18 import java.util.HashMap;
19 import java.util.Map;
20
21 import javax.servlet.ServletContext;
22
23 import org.apache.commons.lang.StringUtils;
24
25 import com.fatwire.gst.foundation.controller.AppContext;
26 import com.fatwire.gst.foundation.facade.logging.Log;
27 import com.fatwire.gst.foundation.facade.logging.LogUtil;
28
29 public class WebAppContext implements AppContext {
30 protected static final Log LOG = LogUtil.getLog(WebAppContext.class);
31
32 public static final String WEB_CONTEXT_NAME = "gsf/AppContext";
33
34 private final ServletContext context;
35 private final AppContext parent;
36
37 private Map<String, Object> localScope = new HashMap<String, Object>();
38
39
40
41
42
43
44
45 public WebAppContext(ServletContext context, AppContext parent) {
46 super();
47 this.context = context;
48 this.parent = parent;
49 }
50
51
52
53
54
55
56 public WebAppContext(ServletContext context) {
57 this(context, null);
58 }
59
60 @SuppressWarnings("unchecked")
61 @Override
62 public final <T> T getBean(String name, Class<T> c) {
63 if (StringUtils.isBlank(name))
64 throw new IllegalArgumentException("name cannot be null or empty");
65
66 if (c.isArray()) {
67 throw new IllegalArgumentException("Arrays are not supported");
68 }
69
70 Object o = null;
71
72 o = localScope.get(name);
73
74 if (o == null) {
75 LOG.debug("Asking for bean by name %s of type %s.",name, c.getName());
76 try {
77
78
79 o = TemplateMethodFactory.createByMethod(this, c);
80 if (o != null && c.isAssignableFrom(o.getClass())) {
81 localScope.put(name, o);
82
83 }
84
85 } catch (final NoSuchMethodException e) {
86
87 try {
88 if (parent != null)
89 o = parent.getBean(name, c);
90
91 else {
92 LOG.debug("Could not create a %s via a Template method, trying via constructor.",c.getName());
93 o = TemplateMethodFactory.createByConstructor(c);
94 if (o != null && c.isAssignableFrom(o.getClass())) {
95 localScope.put(name, o);
96 }
97 }
98 } catch (final RuntimeException e1) {
99 throw e1;
100 } catch (final Exception e1) {
101 throw new RuntimeException(e1);
102 }
103 } catch (final RuntimeException e) {
104 throw e;
105 } catch (final Exception e) {
106 throw new RuntimeException(e);
107 }
108
109 }
110 return (T) o;
111 }
112
113 public ServletContext getServletContext() {
114 return context;
115 }
116
117 @Override
118 public void init() {
119
120
121 }
122 }