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 java.lang.reflect.InvocationTargetException;
25 import java.lang.reflect.Method;
26 import java.net.URL;
27 import java.net.MalformedURLException;
28
29 import org.osgi.framework.BundleContext;
30 import org.osgi.framework.InvalidSyntaxException;
31 import org.osgi.framework.ServiceReference;
32 import org.osgi.framework.Bundle;
33 import com.opensymphony.xwork2.util.logging.Logger;
34 import com.opensymphony.xwork2.util.logging.LoggerFactory;
35
36 public class OsgiUtil {
37 private static final Logger LOG = LoggerFactory.getLogger(OsgiUtil.class);
38
39 /***
40 * A bundle is a jar, and a bunble URL will be useless to clients, this method translates
41 * a URL to a resource inside a bundle from "bundle:something/path" to "jar:file:bundlelocation!/path"
42 */
43 public static URL translateBundleURLToJarURL(URL bundleUrl, Bundle bundle) throws MalformedURLException {
44 if (bundleUrl != null && "bundle".equalsIgnoreCase(bundleUrl.getProtocol())) {
45 StringBuilder sb = new StringBuilder("jar:");
46 sb.append(bundle.getLocation());
47 sb.append("!");
48 sb.append(bundleUrl.getFile());
49 return new URL(sb.toString());
50 }
51
52 return bundleUrl;
53 }
54
55 /***
56 * Calls getBean() on the passed object using refelection. Used on Spring context
57 * because they are loaded from bundles (in anothe class loader)
58 */
59 public static Object getBean(Object beanFactory, String beanId) {
60 try {
61 Method getBeanMethod = beanFactory.getClass().getMethod("getBean", String.class);
62 return getBeanMethod.invoke(beanFactory, beanId);
63 } catch (Exception ex) {
64 if (LOG.isErrorEnabled())
65 LOG.error("Unable to call getBean() on object of type [#0], with bean id [#1]", ex, beanFactory.getClass().getName(), beanId);
66 }
67
68 return null;
69 }
70
71 /***
72 * Calls containsBean on the passed object using refelection. Used on Spring context
73 * because they are loaded from bundles (in anothe class loader)
74 */
75 public static boolean containsBean(Object beanFactory, String beanId) {
76 try {
77 Method getBeanMethod = beanFactory.getClass().getMethod("containsBean", String.class);
78 return (Boolean) getBeanMethod.invoke(beanFactory, beanId);
79 } catch (Exception ex) {
80 if (LOG.isErrorEnabled())
81 LOG.error("Unable to call containsBean() on object of type [#0], with bean id [#1]", ex, beanFactory.getClass().getName(), beanId);
82 }
83
84 return false;
85 }
86 }