1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.ws.test.support;
18
19 import java.util.Map;
20
21 import org.springframework.beans.BeanUtils;
22 import org.springframework.beans.factory.BeanCreationException;
23 import org.springframework.beans.factory.BeanInitializationException;
24 import org.springframework.beans.factory.InitializingBean;
25 import org.springframework.context.ApplicationContext;
26 import org.springframework.context.ApplicationContextAware;
27 import org.springframework.util.Assert;
28 import org.springframework.util.ClassUtils;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32
33
34
35
36
37
38
39 public class MockStrategiesHelper {
40
41 private static final Log logger = LogFactory.getLog(MockStrategiesHelper.class);
42
43 private final ApplicationContext applicationContext;
44
45
46
47
48
49
50 public MockStrategiesHelper(ApplicationContext applicationContext) {
51 Assert.notNull(applicationContext, "'applicationContext' must not be null");
52 this.applicationContext = applicationContext;
53 }
54
55
56
57
58 public ApplicationContext getApplicationContext() {
59 return applicationContext;
60 }
61
62
63
64
65
66
67
68
69 public <T> T getStrategy(Class<T> type) {
70 Assert.notNull(type, "'type' must not be null");
71 Map<String, T> map = applicationContext.getBeansOfType(type);
72 if (map.isEmpty()) {
73 return null;
74 }
75 else if (map.size() == 1) {
76 Map.Entry<String, T> entry = map.entrySet().iterator().next();
77 if (logger.isDebugEnabled()) {
78 logger.debug("Using " + ClassUtils.getShortName(type) + " [" + entry.getKey() + "]");
79 }
80 return entry.getValue();
81 }
82 else {
83 throw new BeanInitializationException(
84 "Could not find exactly 1 " + ClassUtils.getShortName(type) + " in application context");
85 }
86 }
87
88
89
90
91
92
93
94
95
96
97 public <T, D extends T> T getStrategy(Class<T> type, Class<D> defaultType) {
98 Assert.notNull(defaultType, "'defaultType' must not be null");
99 T t = getStrategy(type);
100 if (t != null) {
101 return t;
102 }
103 else {
104 if (logger.isDebugEnabled()) {
105 logger.debug("No " + ClassUtils.getShortName(type) + " found, using default " +
106 ClassUtils.getShortName(defaultType));
107 }
108 T defaultStrategy = BeanUtils.instantiateClass(defaultType);
109 if (defaultStrategy instanceof ApplicationContextAware) {
110 ApplicationContextAware applicationContextAware = (ApplicationContextAware) defaultStrategy;
111 applicationContextAware.setApplicationContext(applicationContext);
112 }
113 if (defaultStrategy instanceof InitializingBean) {
114 InitializingBean initializingBean = (InitializingBean) defaultStrategy;
115 try {
116 initializingBean.afterPropertiesSet();
117 }
118 catch (Exception ex) {
119 throw new BeanCreationException("Invocation of init method failed", ex);
120 }
121 }
122 return defaultStrategy;
123 }
124 }
125
126
127 }