summaryrefslogtreecommitdiffstats
path: root/sandbox/mobile-android/core-android/src/main/java/org/apache/tuscany/sca/core/assembly/CompositeActivatorImpl.java
blob: f730b2ff719df5d007c9d33fc5aedc4b26b4449a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */

package org.apache.tuscany.sca.core.assembly;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.tuscany.sca.assembly.AssemblyFactory;
import org.apache.tuscany.sca.assembly.Binding;
import org.apache.tuscany.sca.assembly.Component;
import org.apache.tuscany.sca.assembly.ComponentReference;
import org.apache.tuscany.sca.assembly.ComponentService;
import org.apache.tuscany.sca.assembly.Composite;
import org.apache.tuscany.sca.assembly.Implementation;
import org.apache.tuscany.sca.assembly.OptimizableBinding;
import org.apache.tuscany.sca.assembly.Reference;
import org.apache.tuscany.sca.assembly.SCABindingFactory;
import org.apache.tuscany.sca.assembly.Service;
import org.apache.tuscany.sca.context.RequestContextFactory;
import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint;
import org.apache.tuscany.sca.core.context.ComponentContextHelper;
import org.apache.tuscany.sca.core.context.ComponentContextImpl;
import org.apache.tuscany.sca.core.conversation.ConversationManager;
import org.apache.tuscany.sca.core.invocation.ProxyFactory;
import org.apache.tuscany.sca.core.scope.ConversationalScopeContainer;
import org.apache.tuscany.sca.core.scope.Scope;
import org.apache.tuscany.sca.core.scope.ScopeContainer;
import org.apache.tuscany.sca.core.scope.ScopeRegistry;
import org.apache.tuscany.sca.core.scope.ScopedRuntimeComponent;
import org.apache.tuscany.sca.interfacedef.InterfaceContract;
import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper;
import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory;
import org.apache.tuscany.sca.invocation.MessageFactory;
import org.apache.tuscany.sca.provider.BindingProviderFactory;
import org.apache.tuscany.sca.provider.ImplementationProvider;
import org.apache.tuscany.sca.provider.ImplementationProviderFactory;
import org.apache.tuscany.sca.provider.PolicyProvider;
import org.apache.tuscany.sca.provider.PolicyProviderFactory;
import org.apache.tuscany.sca.provider.ProviderFactoryExtensionPoint;
import org.apache.tuscany.sca.provider.ReferenceBindingProvider;
import org.apache.tuscany.sca.provider.ServiceBindingProvider;
import org.apache.tuscany.sca.runtime.EndpointReference;
import org.apache.tuscany.sca.runtime.RuntimeComponent;
import org.apache.tuscany.sca.runtime.RuntimeComponentContext;
import org.apache.tuscany.sca.runtime.RuntimeComponentReference;
import org.apache.tuscany.sca.runtime.RuntimeComponentService;
import org.apache.tuscany.sca.runtime.RuntimeWire;
import org.apache.tuscany.sca.runtime.RuntimeWireProcessor;
import org.apache.tuscany.sca.work.WorkScheduler;

/**
 * @version $Rev: 639277 $ $Date: 2008-03-20 06:02:37 -0700 (Thu, 20 Mar 2008) $
 */
public class CompositeActivatorImpl implements CompositeActivator {
    private final static Logger logger = Logger.getLogger(CompositeActivatorImpl.class.getName());

    private final AssemblyFactory assemblyFactory;
    private final MessageFactory messageFactory;
    private final InterfaceContractMapper interfaceContractMapper;
    private final ScopeRegistry scopeRegistry;
    private final WorkScheduler workScheduler;
    private final RuntimeWireProcessor wireProcessor;
    private final ProviderFactoryExtensionPoint providerFactories;

    private final RequestContextFactory requestContextFactory;
    private final ProxyFactory proxyFactory;
    private final JavaInterfaceFactory javaInterfaceFactory;
    private final ConversationManager conversationManager;

    private final ComponentContextHelper componentContextHelper;

    private Composite domainComposite;

    /**
     * @param assemblyFactory
     * @param interfaceContractMapper
     * @param workScheduler
     * @param conversationManager TODO
     * @param workContext
     * @param wirePostProcessorRegistry
     */
    public CompositeActivatorImpl(AssemblyFactory assemblyFactory,
                                  MessageFactory messageFactory,
                                  JavaInterfaceFactory javaInterfaceFactory,
                                  SCABindingFactory scaBindingFactory,
                                  InterfaceContractMapper interfaceContractMapper,
                                  ScopeRegistry scopeRegistry,
                                  WorkScheduler workScheduler,
                                  RuntimeWireProcessor wireProcessor,
                                  RequestContextFactory requestContextFactory,
                                  ProxyFactory proxyFactory,
                                  ProviderFactoryExtensionPoint providerFactories,
                                  StAXArtifactProcessorExtensionPoint processors,
                                  ConversationManager conversationManager) {
        this.assemblyFactory = assemblyFactory;
        this.messageFactory = messageFactory;
        this.interfaceContractMapper = interfaceContractMapper;
        this.scopeRegistry = scopeRegistry;
        this.workScheduler = workScheduler;
        this.wireProcessor = wireProcessor;
        this.providerFactories = providerFactories;
        this.javaInterfaceFactory = javaInterfaceFactory;
        this.requestContextFactory = requestContextFactory;
        this.proxyFactory = proxyFactory;
        this.conversationManager = conversationManager;
        this.componentContextHelper = new ComponentContextHelper(assemblyFactory, javaInterfaceFactory, processors);
    }

    /**
     * @see org.apache.tuscany.sca.core.assembly.CompositeActivator#activate(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentReference)
     */
    public void activate(RuntimeComponent component, RuntimeComponentReference ref) {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Activating component reference: " + component.getURI() + "#" + ref.getName());
        }
        resolveTargets(ref);
        for (Binding binding : ref.getBindings()) {
            addReferenceBindingProvider(component, ref, binding);
        }
    }

    public void start(RuntimeComponent component, RuntimeComponentReference ref) {
        synchronized (ref) {
            resolveTargets(ref);
            for (Binding binding : ref.getBindings()) {
                ReferenceBindingProvider provider = ref.getBindingProvider(binding);
                if (provider == null) {
                    provider = addReferenceBindingProvider(component, ref, binding);
                }
                if (provider != null) {
                    provider.start();
                }
                addReferenceWire(component, ref, binding);
            }
        }
    }
    
    public void stop(Component component, ComponentReference reference)
    {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Starting component reference: " + component.getURI() + "#" + reference.getName());
        }
        RuntimeComponentReference runtimeRef = ((RuntimeComponentReference)reference);
        for (Binding binding : reference.getBindings()) {
            ReferenceBindingProvider bindingProvider = runtimeRef.getBindingProvider(binding);
            if (bindingProvider != null) {
                bindingProvider.stop();
            }
        }
    }    

    public void deactivate(RuntimeComponent component, RuntimeComponentReference ref) {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Deactivating component reference: " + component.getURI() + "#" + ref.getName());
        }
        removeReferenceWires(ref);
        for (Binding binding : ref.getBindings()) {
            removeReferenceBindingProvider(component, ref, binding);
        }

    }

    /**
     * @param component
     * @param reference
     * @param binding
     */
    private ReferenceBindingProvider addReferenceBindingProvider(RuntimeComponent component,
                                                                 RuntimeComponentReference reference,
                                                                 Binding binding) {
        BindingProviderFactory providerFactory =
            (BindingProviderFactory)providerFactories.getProviderFactory(binding.getClass());
        if (providerFactory != null) {
            @SuppressWarnings("unchecked")
            ReferenceBindingProvider bindingProvider =
                providerFactory.createReferenceBindingProvider((RuntimeComponent)component,
                                                               (RuntimeComponentReference)reference,
                                                               binding);
            if (bindingProvider != null) {
                ((RuntimeComponentReference)reference).setBindingProvider(binding, bindingProvider);
            }
            for (PolicyProviderFactory f : providerFactories.getPolicyProviderFactories()) {
                PolicyProvider policyProvider = f.createReferencePolicyProvider(component, reference, binding);
                if (policyProvider != null) {
                    reference.addPolicyProvider(binding, policyProvider);
                }
            }

            return bindingProvider;
        } else {
            throw new IllegalStateException("Provider factory not found for class: " + binding.getClass().getName());
        }
    }

    /**
     * @param reference
     */
    private void resolveTargets(RuntimeComponentReference reference) {
        
/* Not used now that domain wires are created using the domain wire builder
        // go over any targets that have not been resolved yet (as they are running on other nodes)
        // and try an resolve them remotely
        // TODO - this should work for any kind of wired binding but the only wireable binding 
        //        is currently the SCA binding so we assume that
        for (ComponentService service : reference.getTargets()) {
            if (service.isUnresolved()) {
                for (Binding binding : service.getBindings()) {
                    

                    //binding.setURI(service.getName());
                    
                    // TODO - we should look at all the bindings now associated with the 
                    //        unresolved target but we assume the SCA binding here as
                    //        its currently the only wireable one
                    if (binding instanceof SCABinding) {
                        OptimizableBinding scaBinding = (OptimizableBinding)binding;

                        // clone the SCA binding and fill in service details 
                        // its cloned as each target 
                        SCABinding clonedSCABinding = null;
                        try {
                            clonedSCABinding = (SCABinding)((OptimizableBinding)scaBinding).clone();
                            // TODO - Reusing the name here to store the target name so the 
                            //        binding can be found again once the URI is set to the real endpoint
                            clonedSCABinding.setName(service.getName());
                            clonedSCABinding.setURI(service.getName());
                            // wireable binding stuff needs to go. SCA binding uses it
                            // currently to get to the service to work out if the service
                            // is resolved. 
                            OptimizableBinding endpoint = ((OptimizableBinding)clonedSCABinding);
                            endpoint.setTargetComponentService(service);
                            //endpoint.setTargetComponent(component); - not known for unresolved target
                            //endpoint.setTargetBinding(serviceBinding); - not known for unresolved target

                            // add the cloned SCA binding to the reference as it will be used to look up the 
                            // provider later
                            reference.getBindings().remove(binding);
                            reference.getBindings().add(clonedSCABinding);
                        } catch (Exception e) {
                            // warning("The binding doesn't support clone: " + binding.getClass().getSimpleName(), binding);
                        }
                    } else {
                        
                         * Just leave the binding as it. It will be filled in later 
                         * when the node resolves the targets
                        throw new IllegalStateException(
                                                        "Unable to create a distributed SCA binding provider for reference: " + reference
                                                            .getName()
                                                            + " and target: "
                                                            + service.getName());
                     
                    }
                }
            }
        }
*/        
    }

    /**
     * Create the runtime wires for a reference binding
     * 
     * @param component
     * @param reference
     * @param binding
     */
    private void addReferenceWire(Component component, ComponentReference reference, Binding binding) {
        if (!(reference instanceof RuntimeComponentReference)) {
            return;
        }

        // create wire if binding has an endpoint
        Component targetComponent = null;
        ComponentService targetComponentService = null;
        Binding targetBinding = null;
        if (binding instanceof OptimizableBinding) {
            OptimizableBinding endpoint = (OptimizableBinding)binding;
            targetComponent = endpoint.getTargetComponent();
            targetComponentService = endpoint.getTargetComponentService();
            targetBinding = endpoint.getTargetBinding();
        }

        // create a forward wire, either static or dynamic
        addReferenceWire(component, reference, binding, targetComponent, targetComponentService, targetBinding);

        /*
        // if static forward wire (not from self-reference), try to create a static callback wire 
        if (targetComponentService != null && !reference.getName().startsWith("$self$.")) {
            ComponentReference callbackReference = targetComponentService.getCallbackReference();
            if (callbackReference != null) {
                Binding callbackBinding = null;
                Binding callbackServiceBinding = null;
                // select a service callback binding that can be wired back to this component
                for (Binding refBinding : callbackReference.getBindings()) {
                    // first look for a callback binding whose name matches the target binding name
                    if (refBinding.getName().equals(targetBinding.getName())) {
                        callbackBinding = refBinding;
                        break;
                    }
                }
                // see if there is a matching reference callback binding 
                if (callbackBinding != null) {
                    callbackServiceBinding = reference.getCallbackService().getBinding(callbackBinding.getClass());
                }
                // if there isn't an end-to-end match, try again based on target binding type
                if (callbackBinding == null || callbackServiceBinding == null) {
                    callbackBinding = callbackReference.getBinding(targetBinding.getClass());
                    if (callbackBinding != null) {
                        callbackServiceBinding = reference.getCallbackService().getBinding(callbackBinding.getClass());
                    }
                }
                if (callbackBinding != null && callbackServiceBinding != null) {
                    // end-to-end match, so create a static callback wire as well as the static forward wire
        
                    addReferenceWire(targetComponent, callbackReference, callbackBinding, component, reference
                        .getCallbackService(), callbackServiceBinding);
                } else {
                    // no end-to-end match, so do not create a static callback wire
                }
            }
        }
        */
    }

    /**
     * Create a reference wire for a forward call or a callback
     * @param reference
     * @param service
     * @param serviceBinding
     * @param component
     * @param referenceBinding
     */
    private RuntimeWire addReferenceWire(Component refComponent,
                                         ComponentReference reference,
                                         Binding refBinding,
                                         Component serviceComponent,
                                         ComponentService service,
                                         Binding serviceBinding) {
        RuntimeComponentReference runtimeRef = (RuntimeComponentReference)reference;
        InterfaceContract bindingContract = getInterfaceContract(reference, refBinding);

        // Use the interface contract of the reference on the component type
        Reference componentTypeRef = reference.getReference();
        InterfaceContract sourceContract =
            componentTypeRef == null ? reference.getInterfaceContract() : componentTypeRef.getInterfaceContract();
        sourceContract = sourceContract.makeUnidirectional(false);

        EndpointReference wireSource =
            new EndpointReferenceImpl((RuntimeComponent)refComponent, reference, refBinding, sourceContract);
        ComponentService callbackService = reference.getCallbackService();
        if (callbackService != null) {
            // select a reference callback binding to pass with invocations on this wire
            Binding callbackBinding = null;
            for (Binding binding : callbackService.getBindings()) {
                // first look for a callback binding whose name matches the reference binding name
            	if (refBinding.getName().startsWith(binding.getName())) {
                    callbackBinding = binding;
                    break;
                }
            }
            // if no callback binding found, try again based on reference binding type
            if (callbackBinding == null) {
                callbackBinding = callbackService.getBinding(refBinding.getClass());
            }
            InterfaceContract callbackContract = callbackService.getInterfaceContract();
            EndpointReference callbackEndpoint =
                new EndpointReferenceImpl((RuntimeComponent)refComponent, callbackService, callbackBinding,
                                          callbackContract);
            wireSource.setCallbackEndpoint(callbackEndpoint);
        }

        EndpointReference wireTarget =
            new EndpointReferenceImpl((RuntimeComponent)serviceComponent, service, serviceBinding, bindingContract);

        RuntimeWire wire =
            new RuntimeWireImpl(wireSource, wireTarget, interfaceContractMapper, workScheduler, wireProcessor,
                                messageFactory, conversationManager);
        runtimeRef.getRuntimeWires().add(wire);

        return wire;
    }

    private void addImplementationProvider(RuntimeComponent component, Implementation implementation) {
        ImplementationProviderFactory providerFactory =
            (ImplementationProviderFactory)providerFactories.getProviderFactory(implementation.getClass());
        if (providerFactory != null) {
            @SuppressWarnings("unchecked")
            ImplementationProvider implementationProvider =
                providerFactory.createImplementationProvider(component, implementation);
            if (implementationProvider != null) {
                component.setImplementationProvider(implementationProvider);
            }
        } else {
            throw new IllegalStateException("Provider factory not found for class: " + implementation.getClass()
                .getName());
        }
        for (PolicyProviderFactory f : providerFactories.getPolicyProviderFactories()) {
            PolicyProvider policyProvider = f.createImplementationPolicyProvider(component, implementation);
            if (policyProvider != null) {
                component.addPolicyProvider(policyProvider);
            }
        }
        
    }

    private void removeImplementationProvider(RuntimeComponent component) {
        component.setImplementationProvider(null);
        component.getPolicyProviders().clear();
    }

    /**
     * @param component
     * @param service
     * @param binding
     */
    private ServiceBindingProvider addServiceBindingProvider(RuntimeComponent component,
                                                             RuntimeComponentService service,
                                                             Binding binding) {
        BindingProviderFactory providerFactory =
            (BindingProviderFactory)providerFactories.getProviderFactory(binding.getClass());
        if (providerFactory != null) {
            @SuppressWarnings("unchecked")
            ServiceBindingProvider bindingProvider =
                providerFactory.createServiceBindingProvider((RuntimeComponent)component,
                                                             (RuntimeComponentService)service,
                                                             binding);
            if (bindingProvider != null) {
                ((RuntimeComponentService)service).setBindingProvider(binding, bindingProvider);
            }
            for (PolicyProviderFactory f : providerFactories.getPolicyProviderFactories()) {
                PolicyProvider policyProvider = f.createServicePolicyProvider(component, service, binding);
                if (policyProvider != null) {
                    service.addPolicyProvider(binding, policyProvider);
                }
            }
            return bindingProvider;
        } else {
            throw new IllegalStateException("Provider factory not found for class: " + binding.getClass().getName());
        }
    }

    private void removeServiceBindingProvider(RuntimeComponent component,
                                              RuntimeComponentService service,
                                              Binding binding) {
        service.setBindingProvider(binding, null);
        for (Binding b : service.getBindings()) {
            List<PolicyProvider> pps = service.getPolicyProviders(b);
            if (pps != null) {
                pps.clear();
            }
        }
    }

    private void removeReferenceBindingProvider(RuntimeComponent component,
                                                RuntimeComponentReference reference,
                                                Binding binding) {
        reference.setBindingProvider(binding, null);
        for (Binding b : reference.getBindings()) {
            List<PolicyProvider> pps = reference.getPolicyProviders(b);
            if (pps != null) {
                pps.clear();
            }
        }
    }

    public void start(Composite composite) {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Starting composite: " + composite.getName());
        }
        for (Component component : composite.getComponents()) {
            start(component);
        }
    }

    public void stop(Composite composite) {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Stopping composite: " + composite.getName());
        }
        for (Component component : composite.getComponents()) {
            stop(component);
        }
    }

    public void start(Component component) {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Starting component: " + component.getURI());
        }
        RuntimeComponent runtimeComponent = ((RuntimeComponent)component);
        if(runtimeComponent.isStarted()) {
        	return;
        }
        
        configureComponentContext(runtimeComponent);

        for (ComponentReference reference : component.getReferences()) {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Starting component reference: " + component.getURI() + "#" + reference.getName());
            }
            RuntimeComponentReference runtimeRef = ((RuntimeComponentReference)reference);
            runtimeRef.setComponent(runtimeComponent);
            for (Binding binding : reference.getBindings()) {
                ReferenceBindingProvider bindingProvider = runtimeRef.getBindingProvider(binding);
                if (bindingProvider != null) {
                    bindingProvider.start();
                }
            }
        }

        for (ComponentService service : component.getServices()) {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Starting component service: " + component.getURI() + "#" + service.getName());
            }
            RuntimeComponentService runtimeService = (RuntimeComponentService)service;
            for (Binding binding : service.getBindings()) {
                ServiceBindingProvider bindingProvider = runtimeService.getBindingProvider(binding);
                if (bindingProvider != null) {
                    bindingProvider.start();
                }
            }
        }

        Implementation implementation = component.getImplementation();
        if (implementation instanceof Composite) {
            start((Composite)implementation);
        } else {
            ImplementationProvider implementationProvider = runtimeComponent.getImplementationProvider();
            if (implementationProvider != null) {
                implementationProvider.start();
            }
        }

        if (component instanceof ScopedRuntimeComponent) {
            ScopedRuntimeComponent scopedRuntimeComponent = (ScopedRuntimeComponent)component;
            if (scopedRuntimeComponent.getScopeContainer() != null) {
                scopedRuntimeComponent.getScopeContainer().start();
            }
        }

        runtimeComponent.setStarted(true);
    }

    /**
     * @param runtimeComponent
     */
    public void configureComponentContext(RuntimeComponent runtimeComponent) {
        RuntimeComponentContext componentContext =
            new ComponentContextImpl(this, assemblyFactory, proxyFactory, interfaceContractMapper,
                                     requestContextFactory, javaInterfaceFactory, runtimeComponent);
        runtimeComponent.setComponentContext(componentContext);
    }

    /**
     * Stop a component
     */
    public void stop(Component component) {
    	if (!((RuntimeComponent)component).isStarted()) {
    		return;
        }
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Stopping component: " + component.getURI());
        }
        for (ComponentService service : component.getServices()) {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Stopping component service: " + component.getURI() + "#" + service.getName());
            }
            for (Binding binding : service.getBindings()) {
                ServiceBindingProvider bindingProvider = ((RuntimeComponentService)service).getBindingProvider(binding);
                if (bindingProvider != null) {
                    bindingProvider.stop();
                }
            }
        }
        for (ComponentReference reference : component.getReferences()) {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Starting component reference: " + component.getURI() + "#" + reference.getName());
            }
            RuntimeComponentReference runtimeRef = ((RuntimeComponentReference)reference);
            for (Binding binding : reference.getBindings()) {
                ReferenceBindingProvider bindingProvider = runtimeRef.getBindingProvider(binding);
                if (bindingProvider != null) {
                    bindingProvider.stop();
                }
            }
        }
        Implementation implementation = component.getImplementation();
        if (implementation instanceof Composite) {
            stop((Composite)implementation);
        } else {
            ImplementationProvider implementationProvider = ((RuntimeComponent)component).getImplementationProvider();
            if (implementationProvider != null) {
                implementationProvider.stop();
            }
        }

        if (component instanceof ScopedRuntimeComponent) {
            ScopedRuntimeComponent runtimeComponent = (ScopedRuntimeComponent)component;
            if (runtimeComponent.getScopeContainer() != null && 
            		runtimeComponent.getScopeContainer().getLifecycleState() != ScopeContainer.STOPPED) {
                runtimeComponent.getScopeContainer().stop();
            }
        }

        ((RuntimeComponent)component).setStarted(false);
    }

    /**
     * Get the effective interface contract for a reference binding
     * 
     * @param reference
     * @param binding
     * @return
     */
    private InterfaceContract getInterfaceContract(ComponentReference reference, Binding binding) {
        InterfaceContract interfaceContract = reference.getInterfaceContract();
        ReferenceBindingProvider provider = ((RuntimeComponentReference)reference).getBindingProvider(binding);
        if (provider != null) {
            InterfaceContract bindingContract = provider.getBindingInterfaceContract();
            if (bindingContract != null) {
                interfaceContract = bindingContract;
            }
        }
        return interfaceContract.makeUnidirectional(false);
    }

    /**
     * Remove the runtime wires for a reference binding
     * @param reference
     */
    private void removeReferenceWires(ComponentReference reference) {
        if (!(reference instanceof RuntimeComponentReference)) {
            return;
        }
        // [rfeng] Comment out the following statements to avoid the on-demand activation
        // RuntimeComponentReference runtimeRef = (RuntimeComponentReference)reference;
        // runtimeRef.getRuntimeWires().clear();
    }

    /**
     * Get the effective interface contract for the service binding
     * 
     * @param service
     * @param binding
     * @return
     */
    private InterfaceContract getInterfaceContract(ComponentService service, Binding binding) {
        InterfaceContract interfaceContract = service.getInterfaceContract();

        ServiceBindingProvider provider = ((RuntimeComponentService)service).getBindingProvider(binding);
        if (provider != null) {
            InterfaceContract bindingContract = provider.getBindingInterfaceContract();
            if (bindingContract != null) {
                interfaceContract = bindingContract;
            }
        }
        return interfaceContract.makeUnidirectional(false);
    }

    /**
     * Remove runtime wires for a service binding
     * 
     * @param component
     * @param service
     */
    private void removeServiceWires(ComponentService service) {
        if (!(service instanceof RuntimeComponentService)) {
            return;
        }
        RuntimeComponentService runtimeService = (RuntimeComponentService)service;
        runtimeService.getRuntimeWires().clear();
    }

    /**
     * Create a service wire for a forward call or a callback
     * @param service
     * @param serviceBinding
     * @param reference
     * @param component
     * @param referenceBinding
     */
    private RuntimeWire addServiceWire(Component serviceComponent, ComponentService service, Binding serviceBinding) {
        if (!(service instanceof RuntimeComponentService)) {
            return null;
        }
        RuntimeComponentService runtimeService = (RuntimeComponentService)service;

        // FIXME: [rfeng] We might need a better way to get the impl interface contract
        Service targetService = service.getService();
        if (targetService == null) {
            targetService = service;
        }
        InterfaceContract targetContract = targetService.getInterfaceContract().makeUnidirectional(false);

        InterfaceContract sourceContract = getInterfaceContract(service, serviceBinding);

        EndpointReference wireSource = new EndpointReferenceImpl(null, null, serviceBinding, sourceContract);

        EndpointReference wireTarget =
            new EndpointReferenceImpl((RuntimeComponent)serviceComponent, (RuntimeComponentService)service,
                                      serviceBinding, targetContract);

        RuntimeWire wire =
            new RuntimeWireImpl(wireSource, wireTarget, interfaceContractMapper, workScheduler, wireProcessor,
                                messageFactory, conversationManager);
        runtimeService.getRuntimeWires().add(wire);

        return wire;
    }

    public void activate(RuntimeComponent component, RuntimeComponentService service) {
        if (service.getService() == null) {
            if (logger.isLoggable(Level.WARNING)) {
                logger.warning("Skipping component service not defined in the component type: " + component.getURI()
                    + "#"
                    + service.getName());
            }
            return;
        }
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Activating component service: " + component.getURI() + "#" + service.getName());
        }

        for (Binding binding : service.getBindings()) {
            addServiceBindingProvider(component, service, binding);
            addServiceWire(component, service, binding);
        }
    }

    public void deactivate(RuntimeComponent component, RuntimeComponentService service) {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Deactivating component service: " + component.getURI() + "#" + service.getName());
        }
        removeServiceWires(service);
        for (Binding binding : service.getBindings()) {
            removeServiceBindingProvider(component, service, binding);
        }
    }

    private void addScopeContainer(Component component) {
        if (!(component instanceof ScopedRuntimeComponent)) {
            return;
        }
        ScopedRuntimeComponent runtimeComponent = (ScopedRuntimeComponent)component;
        ScopeContainer scopeContainer = scopeRegistry.getScopeContainer(runtimeComponent);
        if (scopeContainer != null && scopeContainer.getScope() == Scope.CONVERSATION) {
            conversationManager.addListener((ConversationalScopeContainer)scopeContainer);
        }
        runtimeComponent.setScopeContainer(scopeContainer);
    }

    private void removeScopeContainer(Component component) {
        if (!(component instanceof ScopedRuntimeComponent)) {
            return;
        }
        ScopedRuntimeComponent runtimeComponent = (ScopedRuntimeComponent)component;
        ScopeContainer scopeContainer = runtimeComponent.getScopeContainer();
        if(scopeContainer != null && scopeContainer.getScope() == Scope.CONVERSATION) {
            conversationManager.removeListener((ConversationalScopeContainer) scopeContainer);
        }        
        runtimeComponent.setScopeContainer(null);
    }
    
    public void activateComponent(Component component)
            throws ActivationException {
        try {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Activating component: " + component.getURI());
            }

            Implementation implementation = component.getImplementation();
            if (implementation instanceof Composite) {
                activate((Composite) implementation);
            } else if (implementation != null) {
                addImplementationProvider((RuntimeComponent) component,
                        implementation);
                addScopeContainer(component);
            }

            for (ComponentService service : component.getServices()) {
                activate((RuntimeComponent) component,
                        (RuntimeComponentService) service);
            }

            for (ComponentReference reference : component.getReferences()) {
                activate((RuntimeComponent) component,
                        (RuntimeComponentReference) reference);
            }
        } catch (Exception e) {
            throw new ActivationException(e);
        }
    }

    public void deactivateComponent(Component component)
            throws ActivationException {
        try {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Deactivating component: " + component.getURI());
            }
            for (ComponentService service : component.getServices()) {
                deactivate((RuntimeComponent) component,
                        (RuntimeComponentService) service);
            }

            for (ComponentReference reference : component.getReferences()) {
                deactivate((RuntimeComponent) component,
                        (RuntimeComponentReference) reference);
            }

            Implementation implementation = component.getImplementation();
            if (implementation instanceof Composite) {
                deactivate((Composite) implementation);
            } else if (implementation != null) {
                removeImplementationProvider((RuntimeComponent) component);
                removeScopeContainer(component);
            }
        } catch (Exception e) {
            throw new ActivationException(e);
        }
    }    

    public void activate(Composite composite) throws ActivationException {
        try {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Activating composite: " + composite.getName());
            }
            for (Component component : composite.getComponents()) {
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("Activating component: " + component.getURI());
                }

                Implementation implementation = component.getImplementation();
                if (implementation instanceof Composite) {
                    activate((Composite)implementation);
                } else if (implementation != null) {
                    addImplementationProvider((RuntimeComponent)component, implementation);
                    addScopeContainer(component);
                }

                for (ComponentService service : component.getServices()) {
                    activate((RuntimeComponent)component, (RuntimeComponentService)service);
                }

                for (ComponentReference reference : component.getReferences()) {
                    activate((RuntimeComponent)component, (RuntimeComponentReference)reference);
                }
            }
        } catch (Exception e) {
            throw new ActivationException(e);
        }
    }

    public void deactivate(Composite composite) throws ActivationException {
        try {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Deactivating composite: " + composite.getName());
            }
            for (Component component : composite.getComponents()) {
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("Deactivating component: " + component.getURI());
                }
                for (ComponentService service : component.getServices()) {
                    deactivate((RuntimeComponent)component, (RuntimeComponentService)service);
                }

                for (ComponentReference reference : component.getReferences()) {
                    deactivate((RuntimeComponent)component, (RuntimeComponentReference)reference);
                }

                Implementation implementation = component.getImplementation();
                if (implementation instanceof Composite) {
                    deactivate((Composite)implementation);
                } else if (implementation != null) {
                    removeImplementationProvider((RuntimeComponent)component);
                    removeScopeContainer(component);
                }
            }
        } catch (Exception e) {
            throw new ActivationException(e);
        }
    }

    /**
     * @return the referenceHelper
     */
    public ComponentContextHelper getComponentContextHelper() {
        return componentContextHelper;
    }

    /**
     * @return the proxyFactory
     */
    public ProxyFactory getProxyFactory() {
        return proxyFactory;
    }

    /**
     * @return the domainComposite
     */
    public Composite getDomainComposite() {
        return domainComposite;
    }

    /**
     * @param domainComposite the domainComposite to set
     */
    public void setDomainComposite(Composite domainComposite) {
        this.domainComposite = domainComposite;
    }

    public Component resolve(String componentURI) {
        for (Composite composite : domainComposite.getIncludes()) {
            Component component = resolve(composite, componentURI);
            if (component != null) {
                return component;
            }
        }
        return null;
    }

    public Component resolve(Composite composite, String componentURI) {
        for (Component component : composite.getComponents()) {
            String uri = component.getURI();
            if (uri.equals(componentURI)) {
                return component;
            }
            if (componentURI.startsWith(uri)) {
                Implementation implementation = component.getImplementation();
                if (!(implementation instanceof Composite)) {
                    return null;
                }
                return resolve((Composite)implementation, componentURI);
            }
        }
        return null;
    }

    /**
     * @return the javaInterfaceFactory
     */
    public JavaInterfaceFactory getJavaInterfaceFactory() {
        return javaInterfaceFactory;
    }

    /**
     * @return the conversationManager
     */
    public ConversationManager getConversationManager() {
        return conversationManager;
    }
    
}