blob: 9a0d33e46864b366d02aa7724a02bd70800aae1a [file] [log] [blame]
Marcel Offermansa962bc92009-11-21 17:59:33 +00001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
Pierre De Ropd2ec3952009-12-04 22:40:05 +000019package org.apache.felix.dm.impl;
Marcel Offermansa962bc92009-11-21 17:59:33 +000020
21import java.lang.reflect.Constructor;
22import java.lang.reflect.Field;
Marcel Offermansa962bc92009-11-21 17:59:33 +000023import java.lang.reflect.Method;
24import java.lang.reflect.Proxy;
25import java.util.ArrayList;
26import java.util.Dictionary;
27import java.util.Enumeration;
28import java.util.HashMap;
29import java.util.Hashtable;
30import java.util.Iterator;
31import java.util.List;
32import java.util.Map;
33import java.util.Properties;
34
Pierre De Ropd2ec3952009-12-04 22:40:05 +000035import org.apache.felix.dm.DependencyManager;
36import org.apache.felix.dm.dependencies.Dependency;
Pierre De Ropd2ec3952009-12-04 22:40:05 +000037import org.apache.felix.dm.impl.dependencies.DependencyActivation;
38import org.apache.felix.dm.impl.dependencies.DependencyService;
Pierre De Ropd2ec3952009-12-04 22:40:05 +000039import org.apache.felix.dm.management.ServiceComponent;
40import org.apache.felix.dm.management.ServiceComponentDependency;
Pierre De Ropd2ec3952009-12-04 22:40:05 +000041import org.apache.felix.dm.service.Service;
42import org.apache.felix.dm.service.ServiceStateListener;
Marcel Offermansa962bc92009-11-21 17:59:33 +000043import org.osgi.framework.BundleContext;
44import org.osgi.framework.ServiceRegistration;
45
46/**
47 * Service implementation.
48 *
49 * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
50 */
Marcel Offermanse14b3422009-11-25 23:04:32 +000051public class ServiceImpl implements Service, DependencyService, ServiceComponent {
Marcel Offermansa962bc92009-11-21 17:59:33 +000052 private static final Class[] VOID = new Class[] {};
53 private static final ServiceRegistration NULL_REGISTRATION;
54 private static final ServiceStateListener[] SERVICE_STATE_LISTENER_TYPE = new ServiceStateListener[] {};
55
Marcel Offermanse14b3422009-11-25 23:04:32 +000056 private final Object SYNC = new Object();
Marcel Offermansa962bc92009-11-21 17:59:33 +000057 private final BundleContext m_context;
58 private final DependencyManager m_manager;
59
60 // configuration (static)
61 private String m_callbackInit;
62 private String m_callbackStart;
63 private String m_callbackStop;
64 private String m_callbackDestroy;
65 private Object m_serviceName;
66 private Object m_implementation;
Marcel Offermans61a81142010-04-02 15:16:50 +000067 private Object m_callbackInstance;
Marcel Offermansa962bc92009-11-21 17:59:33 +000068
69 // configuration (dynamic, but does not affect state)
70 private Dictionary m_serviceProperties;
71
72 // configuration (dynamic, and affects state)
73 private ArrayList m_dependencies = new ArrayList();
74
75 // runtime state (calculated from dependencies)
76 private State m_state;
77
78 // runtime state (changes because of state changes)
79 private Object m_serviceInstance;
80 private ServiceRegistration m_registration;
Marcel Offermanse14b3422009-11-25 23:04:32 +000081 private boolean m_isBound;
82 private boolean m_isInstantiated;
Marcel Offermansa962bc92009-11-21 17:59:33 +000083
84 // service state listeners
85 private final List m_stateListeners = new ArrayList();
86
87 // work queue
88 private final SerialExecutor m_executor = new SerialExecutor();
89
90 // instance factory
91 private Object m_instanceFactory;
92 private String m_instanceFactoryCreateMethod;
93
94 // composition manager
95 private Object m_compositionManager;
96 private String m_compositionManagerGetMethod;
97 private Object m_compositionManagerInstance;
98
99 // internal logging
100 private final Logger m_logger;
101 private ServiceRegistration m_serviceRegistration;
102 private Map m_autoConfig = new HashMap();
103 private Map m_autoConfigInstance = new HashMap();
104
105 public ServiceImpl(BundleContext context, DependencyManager manager, Logger logger) {
106 m_logger = logger;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000107 m_state = new State((List) m_dependencies.clone(), false, false, false);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000108 m_context = context;
109 m_manager = manager;
110 m_callbackInit = "init";
111 m_callbackStart = "start";
112 m_callbackStop = "stop";
113 m_callbackDestroy = "destroy";
114 m_implementation = null;
115 m_autoConfig.put(BundleContext.class, Boolean.TRUE);
116 m_autoConfig.put(ServiceRegistration.class, Boolean.TRUE);
117 m_autoConfig.put(DependencyManager.class, Boolean.TRUE);
Marcel Offermanse14b3422009-11-25 23:04:32 +0000118 m_autoConfig.put(Service.class, Boolean.TRUE);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000119 }
120
Marcel Offermanse14b3422009-11-25 23:04:32 +0000121 private void calculateStateChanges() {
122 // see if any of the things we did caused a further change of state
123 State oldState, newState;
124 synchronized (m_dependencies) {
125 oldState = m_state;
126 newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
127 m_state = newState;
128 }
129 calculateStateChanges(oldState, newState);
130 }
131
Marcel Offermansa962bc92009-11-21 17:59:33 +0000132 private void calculateStateChanges(final State oldState, final State newState) {
Marcel Offermanse14b3422009-11-25 23:04:32 +0000133 if (oldState.isInactive() && (newState.isTrackingOptional())) {
134 m_executor.enqueue(new Runnable() {
135 public void run() {
136 activateService(newState);
137 }});
138 }
139 if (oldState.isInactive() && (newState.isWaitingForRequired())) {
140 m_executor.enqueue(new Runnable() {
141 public void run() {
142 startTrackingRequired(newState);
143 }});
144 }
145 if (oldState.isWaitingForRequired() && newState.isTrackingOptional()) {
146 m_executor.enqueue(new Runnable() {
147 public void run() {
148 activateService(newState);
149 }});
150 }
151 if ((oldState.isWaitingForRequired()) && newState.isInactive()) {
152 m_executor.enqueue(new Runnable() {
153 public void run() {
154 stopTrackingRequired(oldState);
155 }});
156 }
157 if (oldState.isTrackingOptional() && newState.isWaitingForRequiredInstantiated()) {
158 m_executor.enqueue(new Runnable() {
159 public void run() {
160 // TODO as far as I can see there is nothing left to do here
161 }});
162 }
163 if (oldState.isTrackingOptional() && newState.isWaitingForRequired()) {
164 m_executor.enqueue(new Runnable() {
165 public void run() {
166 deactivateService(oldState);
167 }});
168 }
169 if (oldState.isTrackingOptional() && newState.isBound()) {
170 m_executor.enqueue(new Runnable() {
171 public void run() {
172 bindService(oldState);
173 }});
174 }
175 if (oldState.isTrackingOptional() && newState.isInactive()) {
176 m_executor.enqueue(new Runnable() {
177 public void run() {
178 deactivateService(oldState);
179 stopTrackingRequired(oldState);
180 }});
181 }
182 if (oldState.isWaitingForRequiredInstantiated() && newState.isWaitingForRequired()) {
183 m_executor.enqueue(new Runnable() {
184 public void run() {
185 deactivateService(oldState);
186 }});
187 }
188 if (oldState.isWaitingForRequiredInstantiated() && newState.isInactive()) {
189 m_executor.enqueue(new Runnable() {
190 public void run() {
191 deactivateService(oldState);
192 stopTrackingRequired(oldState);
193 }});
194 }
195 if (oldState.isWaitingForRequiredInstantiated() && newState.isBound()) {
196 m_executor.enqueue(new Runnable() {
197 public void run() {
198 bindService(oldState);
199 }});
200 }
201 if (oldState.isBound() && newState.isWaitingForRequiredInstantiated()) {
202 m_executor.enqueue(new Runnable() {
203 public void run() {
204 unbindService(oldState);
205 }});
206 }
207 if (oldState.isBound() && newState.isWaitingForRequired()) {
208 m_executor.enqueue(new Runnable() {
209 public void run() {
210 unbindService(oldState);
211 deactivateService(oldState);
212 }});
213 }
214 if (oldState.isBound() && newState.isInactive()) {
215 m_executor.enqueue(new Runnable() {
216 public void run() {
217 unbindService(oldState);
218 deactivateService(oldState);
219 stopTrackingRequired(oldState);
220 }});
221 }
222 m_executor.execute();
Marcel Offermansa962bc92009-11-21 17:59:33 +0000223 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000224
Marcel Offermansa962bc92009-11-21 17:59:33 +0000225 public Service add(final Dependency dependency) {
226 State oldState, newState;
227 synchronized (m_dependencies) {
228 oldState = m_state;
229 m_dependencies.add(dependency);
230 }
Marcel Offermans4fd903f2009-12-29 09:18:05 +0000231 if (oldState.isAllRequiredAvailable() || (oldState.isWaitingForRequiredInstantiated() && dependency.isRequired()) || (oldState.isWaitingForRequired() && dependency.isRequired())) {
Pierre De Ropd2ec3952009-12-04 22:40:05 +0000232 ((DependencyActivation) dependency).start(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000233 }
Marcel Offermans4fd903f2009-12-29 09:18:05 +0000234
Marcel Offermansa962bc92009-11-21 17:59:33 +0000235 synchronized (m_dependencies) {
Marcel Offermans306c2522009-12-17 13:57:58 +0000236 // starting the dependency above might have triggered another state change, so
237 // we have to fetch the current state again
238 oldState = m_state;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000239 newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000240 m_state = newState;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000241 }
242 calculateStateChanges(oldState, newState);
243 return this;
244 }
245
246 public Service add(List dependencies) {
247 // TODO review if this can be done more smartly
248 for (int i = 0; i < dependencies.size(); i++) {
249 add((Dependency) dependencies.get(i));
Marcel Offermansa962bc92009-11-21 17:59:33 +0000250 }
251 return this;
252 }
253
254 public Service remove(Dependency dependency) {
255 State oldState, newState;
256 synchronized (m_dependencies) {
257 oldState = m_state;
258 m_dependencies.remove(dependency);
259 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000260 if (oldState.isAllRequiredAvailable() || (oldState.isWaitingForRequired() && dependency.isRequired())) {
Pierre De Ropd2ec3952009-12-04 22:40:05 +0000261 ((DependencyActivation) dependency).stop(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000262 }
263 synchronized (m_dependencies) {
Marcel Offermans306c2522009-12-17 13:57:58 +0000264 // starting the dependency above might have triggered another state change, so
265 // we have to fetch the current state again
266 oldState = m_state;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000267 newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000268 m_state = newState;
269 }
270 calculateStateChanges(oldState, newState);
271 return this;
272 }
273
274 public List getDependencies() {
275 synchronized (m_dependencies) {
276 return (List) m_dependencies.clone();
277 }
278 }
279
280 public ServiceRegistration getServiceRegistration() {
281 return m_registration;
282 }
283
284 public Object getService() {
285 return m_serviceInstance;
286 }
287
288 public void dependencyAvailable(final Dependency dependency) {
289 State oldState, newState;
290 synchronized (m_dependencies) {
291 oldState = m_state;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000292 newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000293 m_state = newState;
294 }
Marcel Offermans6cb7ac22010-01-04 09:32:37 +0000295 if (newState.isAllRequiredAvailable() || newState.isWaitingForRequiredInstantiated()) {
Marcel Offermans84a43ad2009-12-29 14:54:48 +0000296 updateInstance(dependency);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000297 }
Marcel Offermans306c2522009-12-17 13:57:58 +0000298 calculateStateChanges(oldState, newState);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000299 }
300
301 public void dependencyChanged(final Dependency dependency) {
302 State state;
303 synchronized (m_dependencies) {
304 state = m_state;
305 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000306 if (state.isAllRequiredAvailable()) {
Marcel Offermans84a43ad2009-12-29 14:54:48 +0000307 updateInstance(dependency);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000308 }
309 }
310
311 public void dependencyUnavailable(final Dependency dependency) {
312 State oldState, newState;
313 synchronized (m_dependencies) {
314 oldState = m_state;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000315 newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000316 m_state = newState;
317 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000318 if (newState.isAllRequiredAvailable()) {
Marcel Offermans84a43ad2009-12-29 14:54:48 +0000319 updateInstance(dependency);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000320 }
Marcel Offermans306c2522009-12-17 13:57:58 +0000321 calculateStateChanges(oldState, newState);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000322 }
323
324 public synchronized void start() {
Marcel Offermans6358e052010-01-04 14:36:08 +0000325 if (m_serviceRegistration == null) {
326 m_serviceRegistration = m_context.registerService(ServiceComponent.class.getName(), this, null);
327 State oldState, newState;
328 synchronized (m_dependencies) {
329 oldState = m_state;
330 newState = new State((List) m_dependencies.clone(), true, m_isInstantiated, m_isBound);
331 m_state = newState;
332 }
333 calculateStateChanges(oldState, newState);
334 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000335 }
336
337 public synchronized void stop() {
Marcel Offermans6358e052010-01-04 14:36:08 +0000338 if (m_serviceRegistration != null) {
339 State oldState, newState;
340 synchronized (m_dependencies) {
341 oldState = m_state;
342 newState = new State((List) m_dependencies.clone(), false, m_isInstantiated, m_isBound);
343 m_state = newState;
344 }
345 calculateStateChanges(oldState, newState);
346 m_serviceRegistration.unregister();
347 m_serviceRegistration = null;
348 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000349 }
350
351 public synchronized Service setInterface(String serviceName, Dictionary properties) {
352 ensureNotActive();
353 m_serviceName = serviceName;
354 m_serviceProperties = properties;
355 return this;
356 }
357
358 public synchronized Service setInterface(String[] serviceName, Dictionary properties) {
359 ensureNotActive();
360 m_serviceName = serviceName;
361 m_serviceProperties = properties;
362 return this;
363 }
364
365 public synchronized Service setCallbacks(String init, String start, String stop, String destroy) {
366 ensureNotActive();
367 m_callbackInit = init;
368 m_callbackStart = start;
369 m_callbackStop = stop;
370 m_callbackDestroy = destroy;
371 return this;
372 }
Marcel Offermans61a81142010-04-02 15:16:50 +0000373
374 public synchronized Service setCallbacks(Object instance, String init, String start, String stop, String destroy) {
375 ensureNotActive();
376 m_callbackInstance = instance;
377 m_callbackInit = init;
378 m_callbackStart = start;
379 m_callbackStop = stop;
380 m_callbackDestroy = destroy;
381 return this;
382 }
383
384
Marcel Offermansa962bc92009-11-21 17:59:33 +0000385
386 public synchronized Service setImplementation(Object implementation) {
387 ensureNotActive();
388 m_implementation = implementation;
389 return this;
390 }
391
392 public synchronized Service setFactory(Object factory, String createMethod) {
393 ensureNotActive();
394 m_instanceFactory = factory;
395 m_instanceFactoryCreateMethod = createMethod;
396 return this;
397 }
398
399 public synchronized Service setFactory(String createMethod) {
400 return setFactory(null, createMethod);
401 }
402
403 public synchronized Service setComposition(Object instance, String getMethod) {
404 ensureNotActive();
405 m_compositionManager = instance;
406 m_compositionManagerGetMethod = getMethod;
407 return this;
408 }
409
410 public synchronized Service setComposition(String getMethod) {
411 return setComposition(null, getMethod);
412 }
413
414 public String toString() {
415 return "ServiceImpl[" + m_serviceName + " " + m_implementation + "]";
416 }
417
418 public synchronized Dictionary getServiceProperties() {
419 if (m_serviceProperties != null) {
420 return (Dictionary) ((Hashtable) m_serviceProperties).clone();
421 }
422 return null;
423 }
424
425 public synchronized void setServiceProperties(Dictionary serviceProperties) {
426 m_serviceProperties = serviceProperties;
Marcel Offermans937ab4f2009-12-10 10:53:01 +0000427 if ((m_registration != null) && (m_serviceName != null)) {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000428 m_registration.setProperties(calculateServiceProperties());
429 }
430 }
431
432 // service state listener methods
433 public void addStateListener(ServiceStateListener listener) {
434 synchronized (m_stateListeners) {
435 m_stateListeners.add(listener);
436 }
437 // when we register as a listener and the service is already started
438 // make sure we invoke the right callbacks so the listener knows
439 State state;
440 synchronized (m_dependencies) {
441 state = m_state;
442 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000443 if (state.isAllRequiredAvailable()) {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000444 listener.starting(this);
445 listener.started(this);
446 }
447 }
448
449 public void removeStateListener(ServiceStateListener listener) {
450 synchronized (m_stateListeners) {
451 m_stateListeners.remove(listener);
452 }
453 }
454
Marcel Offermanse14b3422009-11-25 23:04:32 +0000455 public void removeStateListeners() {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000456 synchronized (m_stateListeners) {
457 m_stateListeners.clear();
458 }
459 }
460
461 private void stateListenersStarting() {
462 ServiceStateListener[] list = getListeners();
463 for (int i = 0; i < list.length; i++) {
464 try {
465 list[i].starting(this);
466 }
467 catch (Throwable t) {
468 m_logger.log(Logger.LOG_ERROR, "Error invoking listener starting method.", t);
469 }
470 }
471 }
472
473 private void stateListenersStarted() {
474 ServiceStateListener[] list = getListeners();
475 for (int i = 0; i < list.length; i++) {
476 try {
477 list[i].started(this);
478 }
479 catch (Throwable t) {
480 m_logger.log(Logger.LOG_ERROR, "Error invoking listener started method.", t);
481 }
482 }
483 }
484
485 private void stateListenersStopping() {
486 ServiceStateListener[] list = getListeners();
487 for (int i = 0; i < list.length; i++) {
488 try {
489 list[i].stopping(this);
490 }
491 catch (Throwable t) {
492 m_logger.log(Logger.LOG_ERROR, "Error invoking listener stopping method.", t);
493 }
494 }
495 }
496
497 private void stateListenersStopped() {
498 ServiceStateListener[] list = getListeners();
499 for (int i = 0; i < list.length; i++) {
500 try {
501 list[i].stopped(this);
502 }
503 catch (Throwable t) {
504 m_logger.log(Logger.LOG_ERROR, "Error invoking listener stopped method.", t);
505 }
506 }
507 }
508
509 private ServiceStateListener[] getListeners() {
510 synchronized (m_stateListeners) {
511 return (ServiceStateListener[]) m_stateListeners.toArray(SERVICE_STATE_LISTENER_TYPE);
512 }
513 }
514
Marcel Offermanse14b3422009-11-25 23:04:32 +0000515 private void activateService(State state) {
516 String init;
517 synchronized (this) {
518 init = m_callbackInit;
519 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000520 // service activation logic, first we initialize the service instance itself
521 // meaning it is created if necessary and the bundle context is set
522 initService();
Marcel Offermansa962bc92009-11-21 17:59:33 +0000523 // now is the time to configure the service, meaning all required
524 // dependencies will be set and any callbacks called
525 configureService(state);
Marcel Offermans78e5dfc2009-12-10 13:52:49 +0000526 // flag that our instance has been created
527 m_isInstantiated = true;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000528 // then we invoke the init callback so the service can further initialize
529 // itself
530 invoke(init);
Marcel Offermanse14b3422009-11-25 23:04:32 +0000531 // see if any of this caused further state changes
532 calculateStateChanges();
533 }
534
535 private void bindService(State state) {
536 String start;
537 synchronized (this) {
538 start = m_callbackStart;
539 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000540 // inform the state listeners we're starting
541 stateListenersStarting();
542 // invoke the start callback, since we're now ready to be used
543 invoke(start);
544 // start tracking optional services
545 startTrackingOptional(state);
546 // register the service in the framework's service registry
547 registerService();
548 // inform the state listeners we've started
549 stateListenersStarted();
550 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000551
552 private void unbindService(State state) {
553 String stop;
554 synchronized (this) {
555 stop = m_callbackStop;
556 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000557 // service deactivation logic, first inform the state listeners
558 // we're stopping
559 stateListenersStopping();
560 // then, unregister the service from the framework
561 unregisterService();
562 // stop tracking optional services
563 stopTrackingOptional(state);
564 // invoke the stop callback
565 invoke(stop);
566 // inform the state listeners we've stopped
567 stateListenersStopped();
Marcel Offermanse14b3422009-11-25 23:04:32 +0000568 }
569
570 private void deactivateService(State state) {
571 String destroy;
572 synchronized (this) {
573 destroy = m_callbackDestroy;
574 }
Marcel Offermans78e5dfc2009-12-10 13:52:49 +0000575 // flag that our instance was destroyed
576 m_isInstantiated = false;
Marcel Offermansa962bc92009-11-21 17:59:33 +0000577 // invoke the destroy callback
578 invoke(destroy);
579 // destroy the service instance
580 destroyService(state);
581 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000582
Marcel Offermansa962bc92009-11-21 17:59:33 +0000583 private void invoke(String name) {
584 if (name != null) {
585 // invoke method if it exists
586 try {
Marcel Offermans61a81142010-04-02 15:16:50 +0000587 // if a callback instance was specified, look for the method there, if not, look for the method in the
588 // instance itself
589 Object instance = m_callbackInstance != null ? m_callbackInstance : m_serviceInstance;
590 InvocationUtil.invokeCallbackMethod(instance, name,
591 new Class[][] {{ Object.class, DependencyManager.class, Service.class }, { DependencyManager.class, Service.class }, { Object.class }, {}},
592 new Object[][] {{ m_serviceInstance, m_manager, this }, { m_manager, this }, { m_serviceInstance }, {}});
Marcel Offermansa962bc92009-11-21 17:59:33 +0000593 }
Marcel Offermanse43114b2010-04-04 18:37:44 +0000594 catch (NoSuchMethodException e) {
595 // we ignore the fact that the method was not found
596 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000597 catch (Exception e) {
Marcel Offermanse43114b2010-04-04 18:37:44 +0000598 // but any other exception means that the method was invoked but somehow failed
599 m_logger.log(Logger.LOG_WARNING, "Error trying to invoke method named " + name + ".", e);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000600 }
601 }
602 }
603
604 private void startTrackingOptional(State state) {
605 Iterator i = state.getDependencies().iterator();
606 while (i.hasNext()) {
607 Dependency dependency = (Dependency) i.next();
608 if (!dependency.isRequired()) {
Pierre De Ropd2ec3952009-12-04 22:40:05 +0000609 ((DependencyActivation) dependency).start(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000610 }
611 }
612 }
613
614 private void stopTrackingOptional(State state) {
615 Iterator i = state.getDependencies().iterator();
616 while (i.hasNext()) {
617 Dependency dependency = (Dependency) i.next();
618 if (!dependency.isRequired()) {
Pierre De Ropd2ec3952009-12-04 22:40:05 +0000619 ((DependencyActivation) dependency).stop(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000620 }
621 }
622 }
623
624 private void startTrackingRequired(State state) {
625 Iterator i = state.getDependencies().iterator();
626 while (i.hasNext()) {
627 Dependency dependency = (Dependency) i.next();
628 if (dependency.isRequired()) {
Pierre De Ropd2ec3952009-12-04 22:40:05 +0000629 ((DependencyActivation) dependency).start(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000630 }
631 }
632 }
633
634 private void stopTrackingRequired(State state) {
635 Iterator i = state.getDependencies().iterator();
636 while (i.hasNext()) {
637 Dependency dependency = (Dependency) i.next();
638 if (dependency.isRequired()) {
Pierre De Ropd2ec3952009-12-04 22:40:05 +0000639 ((DependencyActivation) dependency).stop(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000640 }
641 }
642 }
643
644 private Object createInstance(Class clazz) throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException {
645 Constructor constructor = clazz.getConstructor(VOID);
646 constructor.setAccessible(true);
647 return clazz.newInstance();
648 }
649
Marcel Offermanse14b3422009-11-25 23:04:32 +0000650 public void initService() {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000651 if (m_serviceInstance == null) {
652 if (m_implementation instanceof Class) {
653 // instantiate
654 try {
655 m_serviceInstance = createInstance((Class) m_implementation);
656 }
657 catch (Exception e) {
658 m_logger.log(Logger.LOG_ERROR, "Could not create service instance of class " + m_implementation + ".", e);
659 }
660 }
661 else {
662 if (m_instanceFactoryCreateMethod != null) {
663 Object factory = null;
664 if (m_instanceFactory != null) {
665 if (m_instanceFactory instanceof Class) {
666 try {
667 factory = createInstance((Class) m_instanceFactory);
668 }
669 catch (Exception e) {
670 m_logger.log(Logger.LOG_ERROR, "Could not create factory instance of class " + m_instanceFactory + ".", e);
671 }
672 }
673 else {
674 factory = m_instanceFactory;
675 }
676 }
677 else {
678 // TODO review if we want to try to default to something if not specified
679 // for now the JavaDoc of setFactory(method) reflects the fact that we need
680 // to review it
681 }
682 if (factory == null) {
683 m_logger.log(Logger.LOG_ERROR, "Factory cannot be null.");
684 }
685 else {
686 try {
687 Method m = factory.getClass().getDeclaredMethod(m_instanceFactoryCreateMethod, null);
688 m_serviceInstance = m.invoke(factory, null);
689 }
690 catch (Exception e) {
691 m_logger.log(Logger.LOG_ERROR, "Could not create service instance using factory " + factory + " method " + m_instanceFactoryCreateMethod + ".", e);
692 }
693 }
694 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000695 if (m_serviceInstance == null) {
Marcel Offermanscc8adbb2010-02-17 10:20:11 +0000696 if (m_implementation == null) {
697 m_logger.log(Logger.LOG_ERROR, "Implementation cannot be null.");
698 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000699 m_serviceInstance = m_implementation;
700 }
701 }
702 // configure the bundle context
703 if (((Boolean) m_autoConfig.get(BundleContext.class)).booleanValue()) {
704 configureImplementation(BundleContext.class, m_context, (String) m_autoConfigInstance.get(BundleContext.class));
705 }
706 if (((Boolean) m_autoConfig.get(ServiceRegistration.class)).booleanValue()) {
707 configureImplementation(ServiceRegistration.class, NULL_REGISTRATION, (String) m_autoConfigInstance.get(ServiceRegistration.class));
708 }
709 if (((Boolean) m_autoConfig.get(DependencyManager.class)).booleanValue()) {
710 configureImplementation(DependencyManager.class, m_manager, (String) m_autoConfigInstance.get(DependencyManager.class));
711 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000712 if (((Boolean) m_autoConfig.get(Service.class)).booleanValue()) {
713 configureImplementation(Service.class, this, (String) m_autoConfigInstance.get(Service.class));
714 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000715 }
716 }
717
718 public void setAutoConfig(Class clazz, boolean autoConfig) {
719 m_autoConfig.put(clazz, Boolean.valueOf(autoConfig));
720 }
721
722 public void setAutoConfig(Class clazz, String instanceName) {
723 m_autoConfig.put(clazz, Boolean.valueOf(instanceName != null));
724 m_autoConfigInstance.put(clazz, instanceName);
725 }
726
727 private void configureService(State state) {
728 // configure all services (the optional dependencies might be configured
729 // as null objects but that's what we want at this point)
730 configureServices(state);
731 }
732
733 private void destroyService(State state) {
734 unconfigureServices(state);
735 m_serviceInstance = null;
736 }
737
738 private void registerService() {
739 if (m_serviceName != null) {
740 ServiceRegistrationImpl wrapper = new ServiceRegistrationImpl();
741 m_registration = wrapper;
742 if (((Boolean) m_autoConfig.get(ServiceRegistration.class)).booleanValue()) {
743 configureImplementation(ServiceRegistration.class, m_registration, (String) m_autoConfigInstance.get(ServiceRegistration.class));
744 }
745
746 // service name can either be a string or an array of strings
747 ServiceRegistration registration;
748
749 // determine service properties
750 Dictionary properties = calculateServiceProperties();
751
752 // register the service
753 try {
754 if (m_serviceName instanceof String) {
755 registration = m_context.registerService((String) m_serviceName, m_serviceInstance, properties);
756 }
757 else {
758 registration = m_context.registerService((String[]) m_serviceName, m_serviceInstance, properties);
759 }
760 wrapper.setServiceRegistration(registration);
761 }
762 catch (IllegalArgumentException iae) {
763 m_logger.log(Logger.LOG_ERROR, "Could not register service " + m_serviceInstance, iae);
764 // set the registration to an illegal state object, which will make all invocations on this
765 // wrapper fail with an ISE (which also occurs when the SR becomes invalid)
766 wrapper.setIllegalState();
767 }
768 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000769 m_isBound = true;
Marcel Offermansa962bc92009-11-21 17:59:33 +0000770 }
771
772 private Dictionary calculateServiceProperties() {
773 Dictionary properties = new Properties();
774 addTo(properties, m_serviceProperties);
775 for (int i = 0; i < m_dependencies.size(); i++) {
776 Dependency d = (Dependency) m_dependencies.get(i);
Marcel Offermans117aa2f2009-12-10 09:48:17 +0000777 if (d.isPropagated()) {
778 Dictionary dict = d.getProperties();
779 addTo(properties, dict);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000780 }
781 }
782 if (properties.size() == 0) {
783 properties = null;
784 }
785 return properties;
786 }
787
788 private void addTo(Dictionary properties, Dictionary additional) {
789 if (properties == null) {
790 throw new IllegalArgumentException("Dictionary to add to cannot be null.");
791 }
792 if (additional != null) {
793 Enumeration e = additional.keys();
794 while (e.hasMoreElements()) {
795 Object key = e.nextElement();
796 properties.put(key, additional.get(key));
797 }
798 }
799 }
800
801 private void unregisterService() {
Marcel Offermanse14b3422009-11-25 23:04:32 +0000802 m_isBound = false;
Marcel Offermansa962bc92009-11-21 17:59:33 +0000803 if (m_serviceName != null) {
804 m_registration.unregister();
805 configureImplementation(ServiceRegistration.class, NULL_REGISTRATION);
806 }
807 }
808
809 private void updateInstance(Dependency dependency) {
Marcel Offermans937ab4f2009-12-10 10:53:01 +0000810 if (dependency.isAutoConfig()) {
811 configureImplementation(dependency.getAutoConfigType(), dependency.getAutoConfigInstance(), dependency.getAutoConfigName());
812 if (dependency.isPropagated() && m_registration != null) {
813 m_registration.setProperties(calculateServiceProperties());
Marcel Offermansa962bc92009-11-21 17:59:33 +0000814 }
815 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000816 }
817
818 /**
819 * Configure a field in the service implementation. The service implementation
820 * is searched for fields that have the same type as the class that was specified
821 * and for each of these fields, the specified instance is filled in.
822 *
823 * @param clazz the class to search for
824 * @param instance the instance to fill in
825 * @param instanceName the name of the instance to fill in, or <code>null</code> if not used
826 */
827 private void configureImplementation(Class clazz, Object instance, String instanceName) {
828 Object[] instances = getCompositionInstances();
829 if (instances != null) {
830 for (int i = 0; i < instances.length; i++) {
831 Object serviceInstance = instances[i];
832 Class serviceClazz = serviceInstance.getClass();
Marcel Offermansad760672010-03-03 15:30:01 +0000833 if (Proxy.isProxyClass(serviceClazz)) {
834 serviceInstance = Proxy.getInvocationHandler(serviceInstance);
835 serviceClazz = serviceInstance.getClass();
836 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000837 while (serviceClazz != null) {
838 Field[] fields = serviceClazz.getDeclaredFields();
839 for (int j = 0; j < fields.length; j++) {
Marcel Offermans9afe2f52010-05-11 11:33:39 +0000840 Field field = fields[j];
841 Class type = field.getType();
842 if ((instanceName == null && type.equals(clazz))
843 || (instanceName != null && field.getName().equals(instanceName) && type.isAssignableFrom(clazz))) {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000844 try {
Marcel Offermans9afe2f52010-05-11 11:33:39 +0000845 field.setAccessible(true);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000846 // synchronized makes sure the field is actually written to immediately
Marcel Offermanse14b3422009-11-25 23:04:32 +0000847 synchronized (SYNC) {
Marcel Offermans9afe2f52010-05-11 11:33:39 +0000848 field.set(serviceInstance, instance);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000849 }
850 }
851 catch (Exception e) {
Marcel Offermans9afe2f52010-05-11 11:33:39 +0000852 m_logger.log(Logger.LOG_ERROR, "Could not set field " + field, e);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000853 return;
854 }
855 }
856 }
857 serviceClazz = serviceClazz.getSuperclass();
858 }
859 }
860 }
861 }
862
863 public Object[] getCompositionInstances() {
Marcel Offermanse14b3422009-11-25 23:04:32 +0000864 Object[] instances = null;
865 if (m_compositionManagerGetMethod != null) {
866 if (m_compositionManager != null) {
867 m_compositionManagerInstance = m_compositionManager;
868 }
869 else {
870 m_compositionManagerInstance = m_serviceInstance;
871 }
872 if (m_compositionManagerInstance != null) {
873 try {
874 Method m = m_compositionManagerInstance.getClass().getDeclaredMethod(m_compositionManagerGetMethod, null);
875 m.setAccessible(true);
876 instances = (Object[]) m.invoke(m_compositionManagerInstance, null);
877 }
878 catch (Exception e) {
879 m_logger.log(Logger.LOG_ERROR, "Could not obtain instances from the composition manager.", e);
Marcel Offermans80eeafe2009-12-01 22:12:26 +0000880 instances = m_serviceInstance == null ? new Object[] {} : new Object[] { m_serviceInstance };
Marcel Offermanse14b3422009-11-25 23:04:32 +0000881 }
882 }
883 }
884 else {
Marcel Offermans80eeafe2009-12-01 22:12:26 +0000885 instances = m_serviceInstance == null ? new Object[] {} : new Object[] { m_serviceInstance };
Marcel Offermanse14b3422009-11-25 23:04:32 +0000886 }
887 return instances;
Marcel Offermansa962bc92009-11-21 17:59:33 +0000888 }
889
890 private void configureImplementation(Class clazz, Object instance) {
891 configureImplementation(clazz, instance, null);
892 }
893
894 private void configureServices(State state) {
895 Iterator i = state.getDependencies().iterator();
896 while (i.hasNext()) {
897 Dependency dependency = (Dependency) i.next();
Marcel Offermans001db052009-12-08 08:58:40 +0000898 if (dependency.isAutoConfig()) {
899 configureImplementation(dependency.getAutoConfigType(), dependency.getAutoConfigInstance(), dependency.getAutoConfigName());
Marcel Offermanse14b3422009-11-25 23:04:32 +0000900 }
Marcel Offermans001db052009-12-08 08:58:40 +0000901 if (dependency.isRequired()) {
902 dependency.invokeAdded(this);
Marcel Offermanse14b3422009-11-25 23:04:32 +0000903 }
Marcel Offermans001db052009-12-08 08:58:40 +0000904
905
906// if (dependency instanceof ServiceDependencyImpl) {
907// ServiceDependencyImpl sd = (ServiceDependencyImpl) dependency;
908// if (sd.isAutoConfig()) {
909// if (sd.isRequired()) {
910// configureImplementation(sd.getInterface(), sd.getService(), sd.getAutoConfigName());
911// }
912// else {
913// // for optional services, we do an "ad-hoc" lookup to inject the service if it is
914// // already available even though the tracker has not yet been started
915// configureImplementation(sd.getInterface(), sd.lookupService(), sd.getAutoConfigName());
916// }
917// }
918// // for required dependencies, we invoke any callbacks here
919// if (sd.isRequired()) {
920// sd.invokeAdded(this, sd.lookupServiceReference(), sd.lookupService());
921// }
922// }
923// else if (dependency instanceof BundleDependencyImpl) {
924// BundleDependencyImpl bd = (BundleDependencyImpl) dependency;
925// if (bd.isAutoConfig()) {
926// if (bd.isRequired()) {
927// configureImplementation(Bundle.class, bd.getBundle()); // TODO AutoConfigName support
928// }
929// else {
930// // for optional services, we do an "ad-hoc" lookup to inject the service if it is
931// // already available even though the tracker has not yet been started
932//
933// // TODO !!! configureImplementation(sd.getInterface(), sd.lookupService(), sd.getAutoConfigName());
934// }
935// }
936// // for required dependencies, we invoke any callbacks here
937// if (bd.isRequired()) {
938// bd.invokeAdded(this, bd.getBundle());
939// }
940// }
941// else if (dependency instanceof ResourceDependencyImpl) {
942// ResourceDependencyImpl bd = (ResourceDependencyImpl) dependency;
943// if (bd.isAutoConfig()) {
944// if (bd.isRequired()) {
945// configureImplementation(Resource.class, bd.getResource()); // TODO AutoConfigName support
946// }
947// else {
948// // for optional services, we do an "ad-hoc" lookup to inject the service if it is
949// // already available even though the tracker has not yet been started
950//
951// // TODO !!! configureImplementation(sd.getInterface(), sd.lookupService(), sd.getAutoConfigName());
952// }
953// }
954// // for required dependencies, we invoke any callbacks here
955// if (bd.isRequired()) {
956// bd.invokeAdded(this, bd.getResource());
957// }
958// }
959// else if (dependency instanceof ConfigurationDependencyImpl) {
960// ConfigurationDependencyImpl cd = (ConfigurationDependencyImpl) dependency;
961// // for configuration dependencies, we invoke updated
962// try {
963// cd.invokeUpdate(this, this.getService(), cd.getConfiguration());
964// }
965// catch (ConfigurationException e) {
966// // if this happens, it's definitely an inconsistency
967// // when sharing configuration dependencies between services, all implementations
968// // should accept the same configurations
969// e.printStackTrace();
970// }
971// }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000972 }
973 }
974
975 private void unconfigureServices(State state) {
976 Iterator i = state.getDependencies().iterator();
977 while (i.hasNext()) {
978 Dependency dependency = (Dependency) i.next();
Marcel Offermans001db052009-12-08 08:58:40 +0000979 if (dependency.isRequired()) {
980 dependency.invokeRemoved(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000981 }
Marcel Offermans001db052009-12-08 08:58:40 +0000982// if (dependency instanceof ServiceDependencyImpl) {
983// ServiceDependencyImpl sd = (ServiceDependencyImpl) dependency;
984// // for required dependencies, we invoke any callbacks here
985// if (sd.isRequired()) {
986// sd.invokeRemoved(this, sd.lookupServiceReference(), sd.lookupService());
987// }
988// }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000989 }
990 }
991
992 private void ensureNotActive() {
993 State state;
994 synchronized (m_dependencies) {
995 state = m_state;
996 }
997 if (!state.isInactive()) {
998 throw new IllegalStateException("Cannot modify state while active.");
999 }
1000 }
Marcel Offermanse14b3422009-11-25 23:04:32 +00001001
1002 public boolean isRegistered() {
Marcel Offermansa962bc92009-11-21 17:59:33 +00001003 State state;
1004 synchronized (m_dependencies) {
1005 state = m_state;
1006 }
Marcel Offermans0f6605e2009-12-10 10:31:35 +00001007 return (state.isAllRequiredAvailable());
1008 }
1009
Marcel Offermansa962bc92009-11-21 17:59:33 +00001010 // ServiceComponent interface
1011
1012 static class SCDImpl implements ServiceComponentDependency {
1013 private final String m_name;
1014 private final int m_state;
1015 private final String m_type;
1016
1017 public SCDImpl(String name, int state, String type) {
1018 m_name = name;
1019 m_state = state;
1020 m_type = type;
1021 }
1022
1023 public String getName() {
1024 return m_name;
1025 }
1026
1027 public int getState() {
1028 return m_state;
1029 }
1030
1031 public String getType() {
1032 return m_type;
1033 }
1034 }
1035
1036 public ServiceComponentDependency[] getComponentDependencies() {
1037 List deps = getDependencies();
1038 if (deps != null) {
1039 ServiceComponentDependency[] result = new ServiceComponentDependency[deps.size()];
1040 for (int i = 0; i < result.length; i++) {
1041 Dependency dep = (Dependency) deps.get(i);
1042 if (dep instanceof ServiceComponentDependency) {
1043 result[i] = (ServiceComponentDependency) dep;
1044 }
1045 else {
1046 result[i] = new SCDImpl(dep.toString(), (dep.isAvailable() ? 1 : 0) + (dep.isRequired() ? 2 : 0), dep.getClass().getName());
1047 }
1048 }
1049 return result;
1050 }
1051 return null;
1052 }
1053
1054 public String getName() {
1055 if (m_serviceName instanceof String[]) {
1056 StringBuffer sb = new StringBuffer();
1057 String[] names = (String[]) m_serviceName;
1058 for (int i = 0; i < names.length; i++) {
1059 if (i > 0) {
1060 sb.append(", ");
1061 }
1062 sb.append(names[i]);
1063 }
1064 return sb.toString();
1065 }
1066 else if (m_serviceName instanceof String) {
1067 return m_serviceName.toString();
1068 }
1069 else {
1070 return m_implementation.toString();
1071 }
1072 }
1073
1074 public int getState() {
1075 return (isRegistered() ? 1 : 0);
1076 }
1077
1078 static {
1079 NULL_REGISTRATION = (ServiceRegistration) Proxy.newProxyInstance(ServiceImpl.class.getClassLoader(), new Class[] {ServiceRegistration.class}, new DefaultNullObject());
1080 }
1081}