1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.apache.struts2.osgi;
23
24 import com.opensymphony.xwork2.ObjectFactory;
25 import com.opensymphony.xwork2.util.ClassLoaderUtil;
26 import com.opensymphony.xwork2.inject.Inject;
27 import org.osgi.framework.ServiceReference;
28
29 import java.util.Map;
30
31 /***
32 * This Object factory uses the ActionContext(s) published by Spring OSGi
33 * to lookup beans
34 */
35 public class SpringOsgiObjectFactory extends ObjectFactory {
36 private final static String SPRING_SERVICE_NAME = "org.springframework.context.ApplicationContext";
37
38 private BundleAccessor bundleAccessor;
39
40 public Object buildBean(String className, Map<String, Object> extraContext, boolean injectInternal) throws Exception {
41 if (containsBean(className))
42 return getBean(className);
43 else {
44 Class clazz = ClassLoaderUtil.loadClass(className, SpringOsgiObjectFactory.class);
45 Object object = clazz.newInstance();
46 if (injectInternal)
47 injectInternalBeans(object);
48 return object;
49 }
50
51 }
52
53 public Object buildBean(Class clazz, Map<String, Object> extraContext) throws Exception {
54 return clazz.newInstance();
55 }
56
57 public Class getClassInstance(String className) throws ClassNotFoundException {
58 return containsBean(className) ? getBean(className).getClass() : ClassLoaderUtil.loadClass(className, SpringOsgiObjectFactory.class);
59 }
60
61 protected Object getBean(String beanName) {
62 ServiceReference[] refs = bundleAccessor.getAllServiceReferences(SPRING_SERVICE_NAME);
63 if (refs != null) {
64 for (ServiceReference ref : refs) {
65 Object context = bundleAccessor.getService(ref);
66 if (OsgiUtil.containsBean(context, beanName))
67 return OsgiUtil.getBean(context, beanName);
68 }
69 }
70
71 return null;
72 }
73
74 protected boolean containsBean(String beanName) {
75 ServiceReference[] refs = bundleAccessor.getAllServiceReferences(SPRING_SERVICE_NAME);
76 if (refs != null) {
77 for (ServiceReference ref : refs) {
78 Object context = bundleAccessor.getService(ref);
79 if (OsgiUtil.containsBean(context, beanName))
80 return true;
81 }
82 }
83
84 return false;
85 }
86
87 @Inject
88 public void setBundleAccessor(BundleAccessor bundleAccessor) {
89 this.bundleAccessor = bundleAccessor;
90 }
91 }