blob: 6dc29c11d2735e7357309d4a85f746ef6e81ae0a [file] [log] [blame]
Pierre De Ropb26ca302009-12-04 22:45:59 +00001package org.apache.felix.dm.impl.dependencies;
Marcel Offermansb196d722009-11-26 17:12:12 +00002
3import java.lang.reflect.InvocationTargetException;
4import java.lang.reflect.Method;
5import java.lang.reflect.Modifier;
6
Pierre De Ropb26ca302009-12-04 22:45:59 +00007import org.apache.felix.dm.dependencies.Dependency;
8import org.apache.felix.dm.impl.Logger;
Marcel Offermansb196d722009-11-26 17:12:12 +00009
Pierre De Ropb26ca302009-12-04 22:45:59 +000010public abstract class AbstractDependency implements Dependency, DependencyActivation {
Marcel Offermansb196d722009-11-26 17:12:12 +000011 private boolean m_isRequired;
12 protected final Logger m_logger;
13
14 public AbstractDependency(Logger logger) {
15 m_logger = logger;
16 }
17
18 public synchronized boolean isRequired() {
19 return m_isRequired;
20 }
21
22 protected synchronized void setIsRequired(boolean isRequired) {
23 m_isRequired = isRequired;
24 }
25
26 protected void invokeCallbackMethod(Object[] instances, String methodName, Class[][] signatures, Object[][] parameters) {
27 for (int i = 0; i < instances.length; i++) {
28 try {
29 invokeCallbackMethod(instances[i], methodName, signatures, parameters);
30 }
31 catch (NoSuchMethodException e) {
32 m_logger.log(Logger.LOG_DEBUG, "Method '" + methodName + "' does not exist on " + instances[i] + ". Callback skipped.");
33 }
34 }
35 }
36
37 protected void invokeCallbackMethod(Object instance, String methodName, Class[][] signatures, Object[][] parameters) throws NoSuchMethodException {
38 Class currentClazz = instance.getClass();
39 boolean done = false;
40 while (!done && currentClazz != null) {
41 done = invokeMethod(instance, currentClazz, methodName, signatures, parameters, false);
42 if (!done) {
43 currentClazz = currentClazz.getSuperclass();
44 }
45 }
46 if (!done && currentClazz == null) {
47 throw new NoSuchMethodException(methodName);
48 }
49 }
50
51 protected boolean invokeMethod(Object object, Class clazz, String name, Class[][] signatures, Object[][] parameters, boolean isSuper) {
52 Method m = null;
53 for (int i = 0; i < signatures.length; i++) {
54 Class[] signature = signatures[i];
55 try {
56 m = clazz.getDeclaredMethod(name, signature);
57 if (!(isSuper && Modifier.isPrivate(m.getModifiers()))) {
58 m.setAccessible(true);
59 try {
60 m.invoke(object, parameters[i]);
61 }
62 catch (InvocationTargetException e) {
63 m_logger.log(Logger.LOG_ERROR, "Exception while invoking method " + m + ".", e);
64 }
65 // we did find and invoke the method, so we return true
66 return true;
67 }
68 }
69 catch (NoSuchMethodException e) {
70 // ignore this and keep looking
71 }
72 catch (Exception e) {
73 // could not even try to invoke the method
74 m_logger.log(Logger.LOG_ERROR, "Exception while trying to invoke method " + m + ".", e);
75 }
76 }
77 return false;
78 }
79}