1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.osgi.mock;
18
19 import java.lang.reflect.Constructor;
20 import java.lang.reflect.InvocationTargetException;
21
22 import org.osgi.framework.Filter;
23
24 /**
25 * FrameworkUtil-like class that tries to create a somewhat valid filter.
26 *
27 * Filters objects can be created without an actual OSGi platform running
28 * however, the default OSGi implementation delegates the creation to the
29 * package indicated by "org.osgi.vendor.framework" property.
30 *
31 * In its current implementation, this class requires one of Equinox,
32 * Knoplerfish or Felix on its classpath to create the filter object.
33 *
34 *
35 * @author Costin Leau
36 */
37 public class MockFrameworkUtil {
38
39 private static final String EQUINOX_CLS = "org.eclipse.osgi.framework.internal.core.FilterImpl";
40
41 private static final String KF_CLS = "org.knopflerfish.framework.FilterImpl";
42
43 private static final String FELIX_CLS = "org.apache.felix.framework.FilterImpl";
44
45 private final Constructor filterConstructor;
46
47
48 /**
49 * Constructs a new <code>MockFrameworkUtil</code> instance.
50 *
51 * As opposed to the OSGi approach this class doesn't use statics since it
52 * makes configuration and initialization a lot harder without any
53 * particular benefit.
54 *
55 */
56 MockFrameworkUtil() {
57
58 ClassLoader cl = getClass().getClassLoader();
59 Class filterClz = null;
60
61 filterClz = loadClass(cl, EQUINOX_CLS);
62
63 if (filterClz == null)
64 filterClz = loadClass(cl, KF_CLS);
65
66 if (filterClz == null)
67 filterClz = loadClass(cl, FELIX_CLS);
68
69 if (filterClz == null)
70
71 throw new IllegalStateException("cannot find Equinox, Knopflerfish or Felix on the classpath");
72
73 try {
74 filterConstructor = filterClz.getConstructor(new Class[] { String.class });
75 }
76 catch (NoSuchMethodException e) {
77 throw new IllegalArgumentException("found invalid filter class " + filterClz);
78 }
79 }
80
81 private Class loadClass(ClassLoader loader, String className) {
82 try {
83 return loader.loadClass(className);
84 }
85 catch (ClassNotFoundException e) {
86
87 }
88
89 return null;
90 }
91
92 /**
93 * Create a mock filter that is _might_ be valid. This method does not throw
94 * an checked exception and will always return a filter implementation.
95 *
96 * @param filter OSGi filter given as a String.
97 * @return actual OSGi filter using the underlying OSGi platform
98 */
99 public Filter createFilter(String filter) {
100 try {
101 return (Filter) filterConstructor.newInstance(new Object[] { filter });
102 }
103 catch (IllegalArgumentException e) {
104 throw new RuntimeException(e);
105 }
106 catch (InstantiationException e) {
107 throw new RuntimeException(e);
108 }
109 catch (IllegalAccessException e) {
110 throw new RuntimeException(e);
111 }
112 catch (InvocationTargetException e) {
113 throw new RuntimeException(e);
114 }
115 }
116
117 }