blob: 199aa68b01439d78decf3d54e56c4f041e94c3d0 [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;
23import java.lang.reflect.InvocationTargetException;
24import java.lang.reflect.Method;
25import java.lang.reflect.Proxy;
26import java.util.ArrayList;
27import java.util.Dictionary;
28import java.util.Enumeration;
29import java.util.HashMap;
30import java.util.Hashtable;
31import java.util.Iterator;
32import java.util.List;
33import java.util.Map;
34import java.util.Properties;
35
Pierre De Ropd2ec3952009-12-04 22:40:05 +000036import org.apache.felix.dm.DependencyManager;
37import org.apache.felix.dm.dependencies.Dependency;
Pierre De Ropd2ec3952009-12-04 22:40:05 +000038import org.apache.felix.dm.impl.dependencies.DependencyActivation;
39import org.apache.felix.dm.impl.dependencies.DependencyService;
Pierre De Ropd2ec3952009-12-04 22:40:05 +000040import org.apache.felix.dm.management.ServiceComponent;
41import org.apache.felix.dm.management.ServiceComponentDependency;
Pierre De Ropd2ec3952009-12-04 22:40:05 +000042import org.apache.felix.dm.service.Service;
43import org.apache.felix.dm.service.ServiceStateListener;
Marcel Offermansa962bc92009-11-21 17:59:33 +000044import org.osgi.framework.BundleContext;
45import org.osgi.framework.ServiceRegistration;
46
47/**
48 * Service implementation.
49 *
50 * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
51 */
Marcel Offermanse14b3422009-11-25 23:04:32 +000052public class ServiceImpl implements Service, DependencyService, ServiceComponent {
Marcel Offermansa962bc92009-11-21 17:59:33 +000053 private static final Class[] VOID = new Class[] {};
54 private static final ServiceRegistration NULL_REGISTRATION;
55 private static final ServiceStateListener[] SERVICE_STATE_LISTENER_TYPE = new ServiceStateListener[] {};
56
Marcel Offermanse14b3422009-11-25 23:04:32 +000057 private final Object SYNC = new Object();
Marcel Offermansa962bc92009-11-21 17:59:33 +000058 private final BundleContext m_context;
59 private final DependencyManager m_manager;
60
61 // configuration (static)
62 private String m_callbackInit;
63 private String m_callbackStart;
64 private String m_callbackStop;
65 private String m_callbackDestroy;
66 private Object m_serviceName;
67 private Object m_implementation;
68
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 Offermanse14b3422009-11-25 23:04:32 +0000231 if (oldState.isAllRequiredAvailable() || (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 }
234 synchronized (m_dependencies) {
Marcel Offermanse14b3422009-11-25 23:04:32 +0000235 newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000236 m_state = newState;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000237 }
238 calculateStateChanges(oldState, newState);
239 return this;
240 }
241
242 public Service add(List dependencies) {
243 // TODO review if this can be done more smartly
244 for (int i = 0; i < dependencies.size(); i++) {
245 add((Dependency) dependencies.get(i));
Marcel Offermansa962bc92009-11-21 17:59:33 +0000246 }
247 return this;
248 }
249
250 public Service remove(Dependency dependency) {
251 State oldState, newState;
252 synchronized (m_dependencies) {
253 oldState = m_state;
254 m_dependencies.remove(dependency);
255 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000256 if (oldState.isAllRequiredAvailable() || (oldState.isWaitingForRequired() && dependency.isRequired())) {
Pierre De Ropd2ec3952009-12-04 22:40:05 +0000257 ((DependencyActivation) dependency).stop(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000258 }
259 synchronized (m_dependencies) {
Marcel Offermanse14b3422009-11-25 23:04:32 +0000260 newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000261 m_state = newState;
262 }
263 calculateStateChanges(oldState, newState);
264 return this;
265 }
266
267 public List getDependencies() {
268 synchronized (m_dependencies) {
269 return (List) m_dependencies.clone();
270 }
271 }
272
273 public ServiceRegistration getServiceRegistration() {
274 return m_registration;
275 }
276
277 public Object getService() {
278 return m_serviceInstance;
279 }
280
281 public void dependencyAvailable(final Dependency dependency) {
282 State oldState, newState;
283 synchronized (m_dependencies) {
284 oldState = m_state;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000285 newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000286 m_state = newState;
287 }
288 calculateStateChanges(oldState, newState);
Marcel Offermanse14b3422009-11-25 23:04:32 +0000289 if (newState.isAllRequiredAvailable()) {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000290 m_executor.enqueue(new Runnable() {
291 public void run() {
292 updateInstance(dependency);
293 }
294 });
295 m_executor.execute();
296 }
297 }
298
299 public void dependencyChanged(final Dependency dependency) {
300 State state;
301 synchronized (m_dependencies) {
302 state = m_state;
303 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000304 if (state.isAllRequiredAvailable()) {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000305 m_executor.enqueue(new Runnable() {
306 public void run() {
307 updateInstance(dependency);
308 }
309 });
310 m_executor.execute();
311 }
312 }
313
314 public void dependencyUnavailable(final Dependency dependency) {
315 State oldState, newState;
316 synchronized (m_dependencies) {
317 oldState = m_state;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000318 newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000319 m_state = newState;
320 }
321 calculateStateChanges(oldState, newState);
Marcel Offermanse14b3422009-11-25 23:04:32 +0000322 if (newState.isAllRequiredAvailable()) {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000323 m_executor.enqueue(new Runnable() {
324 public void run() {
325 updateInstance(dependency);
326 }
327 });
328 m_executor.execute();
329 }
330 }
331
332 public synchronized void start() {
333 m_serviceRegistration = m_context.registerService(ServiceComponent.class.getName(), this, null);
334 State oldState, newState;
335 synchronized (m_dependencies) {
336 oldState = m_state;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000337 newState = new State((List) m_dependencies.clone(), true, m_isInstantiated, m_isBound);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000338 m_state = newState;
339 }
340 calculateStateChanges(oldState, newState);
341 }
342
343 public synchronized void stop() {
344 State oldState, newState;
345 synchronized (m_dependencies) {
346 oldState = m_state;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000347 newState = new State((List) m_dependencies.clone(), false, m_isInstantiated, m_isBound);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000348 m_state = newState;
349 }
350 calculateStateChanges(oldState, newState);
351 m_serviceRegistration.unregister();
352 }
353
354 public synchronized Service setInterface(String serviceName, Dictionary properties) {
355 ensureNotActive();
356 m_serviceName = serviceName;
357 m_serviceProperties = properties;
358 return this;
359 }
360
361 public synchronized Service setInterface(String[] serviceName, Dictionary properties) {
362 ensureNotActive();
363 m_serviceName = serviceName;
364 m_serviceProperties = properties;
365 return this;
366 }
367
368 public synchronized Service setCallbacks(String init, String start, String stop, String destroy) {
369 ensureNotActive();
370 m_callbackInit = init;
371 m_callbackStart = start;
372 m_callbackStop = stop;
373 m_callbackDestroy = destroy;
374 return this;
375 }
376
377 public synchronized Service setImplementation(Object implementation) {
378 ensureNotActive();
379 m_implementation = implementation;
380 return this;
381 }
382
383 public synchronized Service setFactory(Object factory, String createMethod) {
384 ensureNotActive();
385 m_instanceFactory = factory;
386 m_instanceFactoryCreateMethod = createMethod;
387 return this;
388 }
389
390 public synchronized Service setFactory(String createMethod) {
391 return setFactory(null, createMethod);
392 }
393
394 public synchronized Service setComposition(Object instance, String getMethod) {
395 ensureNotActive();
396 m_compositionManager = instance;
397 m_compositionManagerGetMethod = getMethod;
398 return this;
399 }
400
401 public synchronized Service setComposition(String getMethod) {
402 return setComposition(null, getMethod);
403 }
404
405 public String toString() {
406 return "ServiceImpl[" + m_serviceName + " " + m_implementation + "]";
407 }
408
409 public synchronized Dictionary getServiceProperties() {
410 if (m_serviceProperties != null) {
411 return (Dictionary) ((Hashtable) m_serviceProperties).clone();
412 }
413 return null;
414 }
415
416 public synchronized void setServiceProperties(Dictionary serviceProperties) {
417 m_serviceProperties = serviceProperties;
Marcel Offermans937ab4f2009-12-10 10:53:01 +0000418 if ((m_registration != null) && (m_serviceName != null)) {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000419 m_registration.setProperties(calculateServiceProperties());
420 }
421 }
422
423 // service state listener methods
424 public void addStateListener(ServiceStateListener listener) {
425 synchronized (m_stateListeners) {
426 m_stateListeners.add(listener);
427 }
428 // when we register as a listener and the service is already started
429 // make sure we invoke the right callbacks so the listener knows
430 State state;
431 synchronized (m_dependencies) {
432 state = m_state;
433 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000434 if (state.isAllRequiredAvailable()) {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000435 listener.starting(this);
436 listener.started(this);
437 }
438 }
439
440 public void removeStateListener(ServiceStateListener listener) {
441 synchronized (m_stateListeners) {
442 m_stateListeners.remove(listener);
443 }
444 }
445
Marcel Offermanse14b3422009-11-25 23:04:32 +0000446 public void removeStateListeners() {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000447 synchronized (m_stateListeners) {
448 m_stateListeners.clear();
449 }
450 }
451
452 private void stateListenersStarting() {
453 ServiceStateListener[] list = getListeners();
454 for (int i = 0; i < list.length; i++) {
455 try {
456 list[i].starting(this);
457 }
458 catch (Throwable t) {
459 m_logger.log(Logger.LOG_ERROR, "Error invoking listener starting method.", t);
460 }
461 }
462 }
463
464 private void stateListenersStarted() {
465 ServiceStateListener[] list = getListeners();
466 for (int i = 0; i < list.length; i++) {
467 try {
468 list[i].started(this);
469 }
470 catch (Throwable t) {
471 m_logger.log(Logger.LOG_ERROR, "Error invoking listener started method.", t);
472 }
473 }
474 }
475
476 private void stateListenersStopping() {
477 ServiceStateListener[] list = getListeners();
478 for (int i = 0; i < list.length; i++) {
479 try {
480 list[i].stopping(this);
481 }
482 catch (Throwable t) {
483 m_logger.log(Logger.LOG_ERROR, "Error invoking listener stopping method.", t);
484 }
485 }
486 }
487
488 private void stateListenersStopped() {
489 ServiceStateListener[] list = getListeners();
490 for (int i = 0; i < list.length; i++) {
491 try {
492 list[i].stopped(this);
493 }
494 catch (Throwable t) {
495 m_logger.log(Logger.LOG_ERROR, "Error invoking listener stopped method.", t);
496 }
497 }
498 }
499
500 private ServiceStateListener[] getListeners() {
501 synchronized (m_stateListeners) {
502 return (ServiceStateListener[]) m_stateListeners.toArray(SERVICE_STATE_LISTENER_TYPE);
503 }
504 }
505
Marcel Offermanse14b3422009-11-25 23:04:32 +0000506 private void activateService(State state) {
507 String init;
508 synchronized (this) {
509 init = m_callbackInit;
510 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000511 // service activation logic, first we initialize the service instance itself
512 // meaning it is created if necessary and the bundle context is set
513 initService();
Marcel Offermansa962bc92009-11-21 17:59:33 +0000514 // now is the time to configure the service, meaning all required
515 // dependencies will be set and any callbacks called
516 configureService(state);
Marcel Offermans78e5dfc2009-12-10 13:52:49 +0000517 // flag that our instance has been created
518 m_isInstantiated = true;
Marcel Offermanse14b3422009-11-25 23:04:32 +0000519 // then we invoke the init callback so the service can further initialize
520 // itself
521 invoke(init);
Marcel Offermanse14b3422009-11-25 23:04:32 +0000522 // see if any of this caused further state changes
523 calculateStateChanges();
524 }
525
526 private void bindService(State state) {
527 String start;
528 synchronized (this) {
529 start = m_callbackStart;
530 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000531 // inform the state listeners we're starting
532 stateListenersStarting();
533 // invoke the start callback, since we're now ready to be used
534 invoke(start);
535 // start tracking optional services
536 startTrackingOptional(state);
537 // register the service in the framework's service registry
538 registerService();
539 // inform the state listeners we've started
540 stateListenersStarted();
541 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000542
543 private void unbindService(State state) {
544 String stop;
545 synchronized (this) {
546 stop = m_callbackStop;
547 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000548 // service deactivation logic, first inform the state listeners
549 // we're stopping
550 stateListenersStopping();
551 // then, unregister the service from the framework
552 unregisterService();
553 // stop tracking optional services
554 stopTrackingOptional(state);
555 // invoke the stop callback
556 invoke(stop);
557 // inform the state listeners we've stopped
558 stateListenersStopped();
Marcel Offermanse14b3422009-11-25 23:04:32 +0000559 }
560
561 private void deactivateService(State state) {
562 String destroy;
563 synchronized (this) {
564 destroy = m_callbackDestroy;
565 }
Marcel Offermans78e5dfc2009-12-10 13:52:49 +0000566 // flag that our instance was destroyed
567 m_isInstantiated = false;
Marcel Offermansa962bc92009-11-21 17:59:33 +0000568 // invoke the destroy callback
569 invoke(destroy);
570 // destroy the service instance
571 destroyService(state);
572 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000573
Marcel Offermansa962bc92009-11-21 17:59:33 +0000574 private void invoke(String name) {
575 if (name != null) {
576 // invoke method if it exists
577 try {
578 Class clazz = m_serviceInstance.getClass();
579 while (clazz != null) {
580 try {
581 Method method = clazz.getDeclaredMethod(name, null);
582 if (method != null) {
583 method.setAccessible(true);
584 try {
585 method.invoke(m_serviceInstance, null);
586 }
587 catch (InvocationTargetException e) {
588 m_logger.log(Logger.LOG_ERROR, "Exception while invoking method " + method + ".", e);
589 }
590 return;
591 }
592 }
593 catch (NoSuchMethodException e) {
594 // ignore this, we keep searching if the method does not exist
595 }
596 clazz = clazz.getSuperclass();
597 }
598 }
599 catch (Exception e) {
600 m_logger.log(Logger.LOG_ERROR, "Error trying to invoke method named " + name + ".", e);
601 }
602 }
603 }
604
605 private void startTrackingOptional(State state) {
606 Iterator i = state.getDependencies().iterator();
607 while (i.hasNext()) {
608 Dependency dependency = (Dependency) i.next();
609 if (!dependency.isRequired()) {
Pierre De Ropd2ec3952009-12-04 22:40:05 +0000610 ((DependencyActivation) dependency).start(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000611 }
612 }
613 }
614
615 private void stopTrackingOptional(State state) {
616 Iterator i = state.getDependencies().iterator();
617 while (i.hasNext()) {
618 Dependency dependency = (Dependency) i.next();
619 if (!dependency.isRequired()) {
Pierre De Ropd2ec3952009-12-04 22:40:05 +0000620 ((DependencyActivation) dependency).stop(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000621 }
622 }
623 }
624
625 private void startTrackingRequired(State state) {
626 Iterator i = state.getDependencies().iterator();
627 while (i.hasNext()) {
628 Dependency dependency = (Dependency) i.next();
629 if (dependency.isRequired()) {
Pierre De Ropd2ec3952009-12-04 22:40:05 +0000630 ((DependencyActivation) dependency).start(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000631 }
632 }
633 }
634
635 private void stopTrackingRequired(State state) {
636 Iterator i = state.getDependencies().iterator();
637 while (i.hasNext()) {
638 Dependency dependency = (Dependency) i.next();
639 if (dependency.isRequired()) {
Pierre De Ropd2ec3952009-12-04 22:40:05 +0000640 ((DependencyActivation) dependency).stop(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000641 }
642 }
643 }
644
645 private Object createInstance(Class clazz) throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException {
646 Constructor constructor = clazz.getConstructor(VOID);
647 constructor.setAccessible(true);
648 return clazz.newInstance();
649 }
650
Marcel Offermanse14b3422009-11-25 23:04:32 +0000651 public void initService() {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000652 if (m_serviceInstance == null) {
653 if (m_implementation instanceof Class) {
654 // instantiate
655 try {
656 m_serviceInstance = createInstance((Class) m_implementation);
657 }
658 catch (Exception e) {
659 m_logger.log(Logger.LOG_ERROR, "Could not create service instance of class " + m_implementation + ".", e);
660 }
661 }
662 else {
663 if (m_instanceFactoryCreateMethod != null) {
664 Object factory = null;
665 if (m_instanceFactory != null) {
666 if (m_instanceFactory instanceof Class) {
667 try {
668 factory = createInstance((Class) m_instanceFactory);
669 }
670 catch (Exception e) {
671 m_logger.log(Logger.LOG_ERROR, "Could not create factory instance of class " + m_instanceFactory + ".", e);
672 }
673 }
674 else {
675 factory = m_instanceFactory;
676 }
677 }
678 else {
679 // TODO review if we want to try to default to something if not specified
680 // for now the JavaDoc of setFactory(method) reflects the fact that we need
681 // to review it
682 }
683 if (factory == null) {
684 m_logger.log(Logger.LOG_ERROR, "Factory cannot be null.");
685 }
686 else {
687 try {
688 Method m = factory.getClass().getDeclaredMethod(m_instanceFactoryCreateMethod, null);
689 m_serviceInstance = m.invoke(factory, null);
690 }
691 catch (Exception e) {
692 m_logger.log(Logger.LOG_ERROR, "Could not create service instance using factory " + factory + " method " + m_instanceFactoryCreateMethod + ".", e);
693 }
694 }
695 }
696 if (m_implementation == null) {
697 m_logger.log(Logger.LOG_ERROR, "Implementation cannot be null.");
698 }
699 if (m_serviceInstance == null) {
700 m_serviceInstance = m_implementation;
701 }
702 }
703 // configure the bundle context
704 if (((Boolean) m_autoConfig.get(BundleContext.class)).booleanValue()) {
705 configureImplementation(BundleContext.class, m_context, (String) m_autoConfigInstance.get(BundleContext.class));
706 }
707 if (((Boolean) m_autoConfig.get(ServiceRegistration.class)).booleanValue()) {
708 configureImplementation(ServiceRegistration.class, NULL_REGISTRATION, (String) m_autoConfigInstance.get(ServiceRegistration.class));
709 }
710 if (((Boolean) m_autoConfig.get(DependencyManager.class)).booleanValue()) {
711 configureImplementation(DependencyManager.class, m_manager, (String) m_autoConfigInstance.get(DependencyManager.class));
712 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000713 if (((Boolean) m_autoConfig.get(Service.class)).booleanValue()) {
714 configureImplementation(Service.class, this, (String) m_autoConfigInstance.get(Service.class));
715 }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000716 }
717 }
718
719 public void setAutoConfig(Class clazz, boolean autoConfig) {
720 m_autoConfig.put(clazz, Boolean.valueOf(autoConfig));
721 }
722
723 public void setAutoConfig(Class clazz, String instanceName) {
724 m_autoConfig.put(clazz, Boolean.valueOf(instanceName != null));
725 m_autoConfigInstance.put(clazz, instanceName);
726 }
727
728 private void configureService(State state) {
729 // configure all services (the optional dependencies might be configured
730 // as null objects but that's what we want at this point)
731 configureServices(state);
732 }
733
734 private void destroyService(State state) {
735 unconfigureServices(state);
736 m_serviceInstance = null;
737 }
738
739 private void registerService() {
740 if (m_serviceName != null) {
741 ServiceRegistrationImpl wrapper = new ServiceRegistrationImpl();
742 m_registration = wrapper;
743 if (((Boolean) m_autoConfig.get(ServiceRegistration.class)).booleanValue()) {
744 configureImplementation(ServiceRegistration.class, m_registration, (String) m_autoConfigInstance.get(ServiceRegistration.class));
745 }
746
747 // service name can either be a string or an array of strings
748 ServiceRegistration registration;
749
750 // determine service properties
751 Dictionary properties = calculateServiceProperties();
752
753 // register the service
754 try {
755 if (m_serviceName instanceof String) {
756 registration = m_context.registerService((String) m_serviceName, m_serviceInstance, properties);
757 }
758 else {
759 registration = m_context.registerService((String[]) m_serviceName, m_serviceInstance, properties);
760 }
761 wrapper.setServiceRegistration(registration);
762 }
763 catch (IllegalArgumentException iae) {
764 m_logger.log(Logger.LOG_ERROR, "Could not register service " + m_serviceInstance, iae);
765 // set the registration to an illegal state object, which will make all invocations on this
766 // wrapper fail with an ISE (which also occurs when the SR becomes invalid)
767 wrapper.setIllegalState();
768 }
769 }
Marcel Offermanse14b3422009-11-25 23:04:32 +0000770 m_isBound = true;
Marcel Offermansa962bc92009-11-21 17:59:33 +0000771 }
772
773 private Dictionary calculateServiceProperties() {
774 Dictionary properties = new Properties();
775 addTo(properties, m_serviceProperties);
776 for (int i = 0; i < m_dependencies.size(); i++) {
777 Dependency d = (Dependency) m_dependencies.get(i);
Marcel Offermans117aa2f2009-12-10 09:48:17 +0000778 if (d.isPropagated()) {
779 Dictionary dict = d.getProperties();
780 addTo(properties, dict);
Marcel Offermansa962bc92009-11-21 17:59:33 +0000781 }
782 }
783 if (properties.size() == 0) {
784 properties = null;
785 }
786 return properties;
787 }
788
789 private void addTo(Dictionary properties, Dictionary additional) {
790 if (properties == null) {
791 throw new IllegalArgumentException("Dictionary to add to cannot be null.");
792 }
793 if (additional != null) {
794 Enumeration e = additional.keys();
795 while (e.hasMoreElements()) {
796 Object key = e.nextElement();
797 properties.put(key, additional.get(key));
798 }
799 }
800 }
801
802 private void unregisterService() {
Marcel Offermanse14b3422009-11-25 23:04:32 +0000803 m_isBound = false;
Marcel Offermansa962bc92009-11-21 17:59:33 +0000804 if (m_serviceName != null) {
805 m_registration.unregister();
806 configureImplementation(ServiceRegistration.class, NULL_REGISTRATION);
807 }
808 }
809
810 private void updateInstance(Dependency dependency) {
Marcel Offermans937ab4f2009-12-10 10:53:01 +0000811
812 if (dependency.isAutoConfig()) {
813 configureImplementation(dependency.getAutoConfigType(), dependency.getAutoConfigInstance(), dependency.getAutoConfigName());
814 if (dependency.isPropagated() && m_registration != null) {
815 m_registration.setProperties(calculateServiceProperties());
Marcel Offermansa962bc92009-11-21 17:59:33 +0000816 }
817 }
Marcel Offermans937ab4f2009-12-10 10:53:01 +0000818
819// if (dependency instanceof ServiceDependencyImpl) {
820// ServiceDependencyImpl sd = (ServiceDependencyImpl) dependency;
821// // update the dependency in the service instance (it will use
822// // a null object if necessary)
823// if (sd.isAutoConfig()) {
824// configureImplementation(sd.getInterface(), sd.getService(), sd.getAutoConfigName());
825// }
826// }
827// else if (dependency instanceof ConfigurationDependencyImpl) {
828// ConfigurationDependencyImpl cd = (ConfigurationDependencyImpl) dependency;
829// if (cd.isPropagated()) {
830// // change service properties accordingly, but only if the service was already registered
831// if (m_registration != null) {
832// Dictionary props = calculateServiceProperties();
833// m_registration.setProperties(props);
834// }
835// }
836// }
837// else if (dependency instanceof BundleDependencyImpl) {
838// BundleDependencyImpl bd = (BundleDependencyImpl) dependency;
839// if (bd.isAutoConfig()) {
840// configureImplementation(Bundle.class, bd.getBundle()); // TODO support AutoConfigName
841// }
842// }
843// else if (dependency instanceof ResourceDependencyImpl) {
844// ResourceDependencyImpl rd = (ResourceDependencyImpl) dependency;
845// if (rd.isAutoConfig()) {
846// configureImplementation(Resource.class, rd.getResource()); // TODO support AutoConfigName
847// }
848// }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000849 }
850
851 /**
852 * Configure a field in the service implementation. The service implementation
853 * is searched for fields that have the same type as the class that was specified
854 * and for each of these fields, the specified instance is filled in.
855 *
856 * @param clazz the class to search for
857 * @param instance the instance to fill in
858 * @param instanceName the name of the instance to fill in, or <code>null</code> if not used
859 */
860 private void configureImplementation(Class clazz, Object instance, String instanceName) {
861 Object[] instances = getCompositionInstances();
862 if (instances != null) {
863 for (int i = 0; i < instances.length; i++) {
864 Object serviceInstance = instances[i];
865 Class serviceClazz = serviceInstance.getClass();
866 while (serviceClazz != null) {
867 Field[] fields = serviceClazz.getDeclaredFields();
868 for (int j = 0; j < fields.length; j++) {
869 if (fields[j].getType().equals(clazz) && (instanceName == null || fields[j].getName().equals(instanceName))) {
870 try {
871 fields[j].setAccessible(true);
872 // synchronized makes sure the field is actually written to immediately
Marcel Offermanse14b3422009-11-25 23:04:32 +0000873 synchronized (SYNC) {
Marcel Offermansa962bc92009-11-21 17:59:33 +0000874 fields[j].set(serviceInstance, instance);
875 }
876 }
877 catch (Exception e) {
878 m_logger.log(Logger.LOG_ERROR, "Could not set field " + fields[j], e);
879 return;
880 }
881 }
882 }
883 serviceClazz = serviceClazz.getSuperclass();
884 }
885 }
886 }
887 }
888
889 public Object[] getCompositionInstances() {
Marcel Offermanse14b3422009-11-25 23:04:32 +0000890 Object[] instances = null;
891 if (m_compositionManagerGetMethod != null) {
892 if (m_compositionManager != null) {
893 m_compositionManagerInstance = m_compositionManager;
894 }
895 else {
896 m_compositionManagerInstance = m_serviceInstance;
897 }
898 if (m_compositionManagerInstance != null) {
899 try {
900 Method m = m_compositionManagerInstance.getClass().getDeclaredMethod(m_compositionManagerGetMethod, null);
901 m.setAccessible(true);
902 instances = (Object[]) m.invoke(m_compositionManagerInstance, null);
903 }
904 catch (Exception e) {
905 m_logger.log(Logger.LOG_ERROR, "Could not obtain instances from the composition manager.", e);
Marcel Offermans80eeafe2009-12-01 22:12:26 +0000906 instances = m_serviceInstance == null ? new Object[] {} : new Object[] { m_serviceInstance };
Marcel Offermanse14b3422009-11-25 23:04:32 +0000907 }
908 }
909 }
910 else {
Marcel Offermans80eeafe2009-12-01 22:12:26 +0000911 instances = m_serviceInstance == null ? new Object[] {} : new Object[] { m_serviceInstance };
Marcel Offermanse14b3422009-11-25 23:04:32 +0000912 }
913 return instances;
Marcel Offermansa962bc92009-11-21 17:59:33 +0000914 }
915
916 private void configureImplementation(Class clazz, Object instance) {
917 configureImplementation(clazz, instance, null);
918 }
919
920 private void configureServices(State state) {
921 Iterator i = state.getDependencies().iterator();
922 while (i.hasNext()) {
923 Dependency dependency = (Dependency) i.next();
Marcel Offermans001db052009-12-08 08:58:40 +0000924 if (dependency.isAutoConfig()) {
925 configureImplementation(dependency.getAutoConfigType(), dependency.getAutoConfigInstance(), dependency.getAutoConfigName());
Marcel Offermanse14b3422009-11-25 23:04:32 +0000926 }
Marcel Offermans001db052009-12-08 08:58:40 +0000927 if (dependency.isRequired()) {
928 dependency.invokeAdded(this);
Marcel Offermanse14b3422009-11-25 23:04:32 +0000929 }
Marcel Offermans001db052009-12-08 08:58:40 +0000930
931
932// if (dependency instanceof ServiceDependencyImpl) {
933// ServiceDependencyImpl sd = (ServiceDependencyImpl) dependency;
934// if (sd.isAutoConfig()) {
935// if (sd.isRequired()) {
936// configureImplementation(sd.getInterface(), sd.getService(), sd.getAutoConfigName());
937// }
938// else {
939// // for optional services, we do an "ad-hoc" lookup to inject the service if it is
940// // already available even though the tracker has not yet been started
941// configureImplementation(sd.getInterface(), sd.lookupService(), sd.getAutoConfigName());
942// }
943// }
944// // for required dependencies, we invoke any callbacks here
945// if (sd.isRequired()) {
946// sd.invokeAdded(this, sd.lookupServiceReference(), sd.lookupService());
947// }
948// }
949// else if (dependency instanceof BundleDependencyImpl) {
950// BundleDependencyImpl bd = (BundleDependencyImpl) dependency;
951// if (bd.isAutoConfig()) {
952// if (bd.isRequired()) {
953// configureImplementation(Bundle.class, bd.getBundle()); // TODO AutoConfigName support
954// }
955// else {
956// // for optional services, we do an "ad-hoc" lookup to inject the service if it is
957// // already available even though the tracker has not yet been started
958//
959// // TODO !!! configureImplementation(sd.getInterface(), sd.lookupService(), sd.getAutoConfigName());
960// }
961// }
962// // for required dependencies, we invoke any callbacks here
963// if (bd.isRequired()) {
964// bd.invokeAdded(this, bd.getBundle());
965// }
966// }
967// else if (dependency instanceof ResourceDependencyImpl) {
968// ResourceDependencyImpl bd = (ResourceDependencyImpl) dependency;
969// if (bd.isAutoConfig()) {
970// if (bd.isRequired()) {
971// configureImplementation(Resource.class, bd.getResource()); // TODO AutoConfigName support
972// }
973// else {
974// // for optional services, we do an "ad-hoc" lookup to inject the service if it is
975// // already available even though the tracker has not yet been started
976//
977// // TODO !!! configureImplementation(sd.getInterface(), sd.lookupService(), sd.getAutoConfigName());
978// }
979// }
980// // for required dependencies, we invoke any callbacks here
981// if (bd.isRequired()) {
982// bd.invokeAdded(this, bd.getResource());
983// }
984// }
985// else if (dependency instanceof ConfigurationDependencyImpl) {
986// ConfigurationDependencyImpl cd = (ConfigurationDependencyImpl) dependency;
987// // for configuration dependencies, we invoke updated
988// try {
989// cd.invokeUpdate(this, this.getService(), cd.getConfiguration());
990// }
991// catch (ConfigurationException e) {
992// // if this happens, it's definitely an inconsistency
993// // when sharing configuration dependencies between services, all implementations
994// // should accept the same configurations
995// e.printStackTrace();
996// }
997// }
Marcel Offermansa962bc92009-11-21 17:59:33 +0000998 }
999 }
1000
1001 private void unconfigureServices(State state) {
1002 Iterator i = state.getDependencies().iterator();
1003 while (i.hasNext()) {
1004 Dependency dependency = (Dependency) i.next();
Marcel Offermans001db052009-12-08 08:58:40 +00001005 if (dependency.isRequired()) {
1006 dependency.invokeRemoved(this);
Marcel Offermansa962bc92009-11-21 17:59:33 +00001007 }
Marcel Offermans001db052009-12-08 08:58:40 +00001008// if (dependency instanceof ServiceDependencyImpl) {
1009// ServiceDependencyImpl sd = (ServiceDependencyImpl) dependency;
1010// // for required dependencies, we invoke any callbacks here
1011// if (sd.isRequired()) {
1012// sd.invokeRemoved(this, sd.lookupServiceReference(), sd.lookupService());
1013// }
1014// }
Marcel Offermansa962bc92009-11-21 17:59:33 +00001015 }
1016 }
1017
1018 private void ensureNotActive() {
1019 State state;
1020 synchronized (m_dependencies) {
1021 state = m_state;
1022 }
1023 if (!state.isInactive()) {
1024 throw new IllegalStateException("Cannot modify state while active.");
1025 }
1026 }
Marcel Offermanse14b3422009-11-25 23:04:32 +00001027
1028 public boolean isRegistered() {
Marcel Offermansa962bc92009-11-21 17:59:33 +00001029 State state;
1030 synchronized (m_dependencies) {
1031 state = m_state;
1032 }
Marcel Offermans0f6605e2009-12-10 10:31:35 +00001033 return (state.isAllRequiredAvailable());
1034 }
1035
Marcel Offermansa962bc92009-11-21 17:59:33 +00001036 // ServiceComponent interface
1037
1038 static class SCDImpl implements ServiceComponentDependency {
1039 private final String m_name;
1040 private final int m_state;
1041 private final String m_type;
1042
1043 public SCDImpl(String name, int state, String type) {
1044 m_name = name;
1045 m_state = state;
1046 m_type = type;
1047 }
1048
1049 public String getName() {
1050 return m_name;
1051 }
1052
1053 public int getState() {
1054 return m_state;
1055 }
1056
1057 public String getType() {
1058 return m_type;
1059 }
1060 }
1061
1062 public ServiceComponentDependency[] getComponentDependencies() {
1063 List deps = getDependencies();
1064 if (deps != null) {
1065 ServiceComponentDependency[] result = new ServiceComponentDependency[deps.size()];
1066 for (int i = 0; i < result.length; i++) {
1067 Dependency dep = (Dependency) deps.get(i);
1068 if (dep instanceof ServiceComponentDependency) {
1069 result[i] = (ServiceComponentDependency) dep;
1070 }
1071 else {
1072 result[i] = new SCDImpl(dep.toString(), (dep.isAvailable() ? 1 : 0) + (dep.isRequired() ? 2 : 0), dep.getClass().getName());
1073 }
1074 }
1075 return result;
1076 }
1077 return null;
1078 }
1079
1080 public String getName() {
1081 if (m_serviceName instanceof String[]) {
1082 StringBuffer sb = new StringBuffer();
1083 String[] names = (String[]) m_serviceName;
1084 for (int i = 0; i < names.length; i++) {
1085 if (i > 0) {
1086 sb.append(", ");
1087 }
1088 sb.append(names[i]);
1089 }
1090 return sb.toString();
1091 }
1092 else if (m_serviceName instanceof String) {
1093 return m_serviceName.toString();
1094 }
1095 else {
1096 return m_implementation.toString();
1097 }
1098 }
1099
1100 public int getState() {
1101 return (isRegistered() ? 1 : 0);
1102 }
1103
1104 static {
1105 NULL_REGISTRATION = (ServiceRegistration) Proxy.newProxyInstance(ServiceImpl.class.getClassLoader(), new Class[] {ServiceRegistration.class}, new DefaultNullObject());
1106 }
1107}