all connect calls are now validated.
[utils] / system / general / src / main / java / org / wamblee / system / container / Container.java
1 /*
2  * Copyright 2007 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.wamblee.system.container;
17
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.HashSet;
21 import java.util.List;
22 import java.util.Set;
23
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26 import org.wamblee.general.Pair;
27 import org.wamblee.system.core.AbstractComponent;
28 import org.wamblee.system.core.Component;
29 import org.wamblee.system.core.DefaultScope;
30 import org.wamblee.system.core.NamedInterface;
31 import org.wamblee.system.core.ProvidedInterface;
32 import org.wamblee.system.core.RequiredInterface;
33 import org.wamblee.system.core.Scope;
34 import org.wamblee.system.core.SystemAssemblyException;
35 import org.wamblee.system.graph.CompositeEdgeFilter;
36 import org.wamblee.system.graph.component.ComponentGraph;
37 import org.wamblee.system.graph.component.ConnectExternalProvidedProvidedFilter;
38 import org.wamblee.system.graph.component.ConnectRequiredExternallyRequiredEdgeFilter;
39 import org.wamblee.system.graph.component.ConnectRequiredProvidedEdgeFilter;
40
41 /**
42  * Container consisting of multiple components.
43  * 
44  * @author Erik Brakkee
45  */
46 public class Container extends AbstractComponent<Scope> {
47
48     private static final Log LOG = LogFactory.getLog(Container.class);
49
50     private List<Component> _components;
51     private CompositeEdgeFilter _edgeFilter; 
52     private boolean _sealed;
53
54     /**
55      * Constructs the container
56      * 
57      * @param aName
58      *            Name of the container
59      * @param aComponents
60      *            Components.
61      * @param aProvided
62      *            Provided services of the container
63      * @param aRequired
64      *            Required services by the container.
65      */
66     public Container(String aName, Component[] aComponents,
67             List<ProvidedInterface> aProvided, List<RequiredInterface> aRequired) {
68         super(aName, aProvided, aRequired);
69         _components = new ArrayList<Component>();
70
71         _edgeFilter = new CompositeEdgeFilter();
72         _sealed = false;
73         for (Component component : aComponents) {
74             addComponent(component);
75         }
76     }
77     
78     /**
79      * Constructs the container
80      * 
81      * @param aName
82      *            Name of the container
83      * @param aComponents
84      *            Components.
85      * @param aProvided
86      *            Provided services of the container
87      * @param aRequired
88      *            Required services by the container.
89      */
90     public Container(String aName, Component[] aComponents,
91             ProvidedInterface[] aProvided, RequiredInterface[] aRequired) {
92         this(aName, aComponents, Arrays.asList(aProvided), Arrays.asList(aRequired));
93     }
94
95     public Container(String aName) {
96         this(aName, new Component[0], new ProvidedInterface[0],
97                 new RequiredInterface[0]);
98     }
99
100     public Container addComponent(Component aComponent) {
101         checkSealed();
102         if (aComponent.getContext() != null) {
103             throw new SystemAssemblyException(
104                     "Inconsistent hierarchy, component '"
105                             + aComponent.getName()
106                             + "' is already part of another hierarchy");
107         }
108         if ( findComponent(aComponent.getName()) != null ) {
109             throw new SystemAssemblyException("Duplicate component '"
110                     + aComponent.getName() + "'");
111         }
112         _components.add(aComponent);
113         aComponent.addContext(getQualifiedName());
114         return this;
115     }
116     
117     /**
118      * Explictly connects required and provided interfaces. 
119      * @param aClientComponent Client component, may not be null. 
120      * @param aRequiredInterface Required interface. If null it means all required interfaces. 
121      * @param aServerComponent Server component to connect to. If null, it means that no server components
122      *         may be connected to and the provider of the required interface will be null. 
123      * @param aProvidedInterface Provided interface. If null, it means that there is no restriction on the 
124      *   name of the provided interface and that it is automatically selected. 
125      */
126     public void connectRequiredProvided(String aClientComponent, String aRequiredInterface, 
127             String aServerComponent, String aProvidedInterface) {
128         checkSealed();
129         Component client = findComponent(aClientComponent);
130         Component server = findComponent(aServerComponent);
131         if ( client == null ) { 
132                 throw new SystemAssemblyException(getQualifiedName() + ": No component '" + aClientComponent + "' in the container");
133         }
134         if ( aRequiredInterface != null ) { 
135                 if ( findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null ) { 
136                         throw new SystemAssemblyException(
137                                         getQualifiedName() + ": Component '" + aClientComponent + "' does not have a required interface named '" 
138                                         + aRequiredInterface + "'");
139                 }
140         }
141         if ( server == null ) { 
142                 throw new SystemAssemblyException("No component '" + aClientComponent + "' in the container");
143         }
144         if ( aProvidedInterface != null ) { 
145                 if ( findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) { 
146                         throw new SystemAssemblyException(
147                                         getQualifiedName() + ": Component '" + aServerComponent + "' does not have a provided interface named '" 
148                                         + aProvidedInterface + "'");
149                 }
150         }
151         _edgeFilter.add(new ConnectRequiredProvidedEdgeFilter(aClientComponent, aRequiredInterface, aServerComponent, aProvidedInterface));
152     }
153     
154     /**
155      * Explicitly connects a externally required interface to an internally required interface. 
156      * @param aComponent Component requiring the interface (must be non-null). 
157      * @param aRequiredInterface Required interface of the component (must be non-null).
158      * @param aExternalRequiredInterface Externally required interface (must be non-null).
159      */
160     public void connectExternalRequired(String aComponent, String aRequiredInterface, 
161             String aExternalRequiredInterface) {
162         checkSealed();
163         Component client = findComponent(aComponent);
164         if ( client == null ) { 
165                 throw new SystemAssemblyException(getQualifiedName() + ": No component '" + aComponent + "' in the container");
166         }
167         if ( aRequiredInterface != null ) { 
168                 if ( findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null ) { 
169                         throw new SystemAssemblyException(
170                                         getQualifiedName() + ": Component '" + aComponent + "' does not have a required interface named '" 
171                                         + aRequiredInterface + "'");
172                 }
173         }
174         if ( aExternalRequiredInterface != null) { 
175                 if ( findInterface(getRequiredInterfaces(), aExternalRequiredInterface) == null ) { 
176                         throw new SystemAssemblyException(
177                                         getQualifiedName() + ": container does not have a required interface named '" 
178                                         + aExternalRequiredInterface + "'");
179                 }
180         }
181         _edgeFilter.add(new ConnectRequiredExternallyRequiredEdgeFilter(
182                 aComponent, aRequiredInterface, aExternalRequiredInterface));
183     }
184     
185     public void connectExternalProvided(String aExternalProvided, String aComponent, String aProvidedInterface) {
186         checkSealed();
187         Component server = findComponent(aComponent);
188        
189       
190         if ( server == null ) { 
191                 throw new SystemAssemblyException("No component '" + aComponent + "' in the container");
192         }
193         if ( aProvidedInterface != null ) { 
194                 if ( findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) { 
195                         throw new SystemAssemblyException(
196                                         getQualifiedName() + ": Component '" + aComponent + "' does not have a provided interface named '" 
197                                         + aProvidedInterface + "'");
198                 }
199         }
200         if ( aExternalProvided != null ) { 
201                 if ( findInterface(getProvidedInterfaces(), aExternalProvided) == null) { 
202                         throw new SystemAssemblyException(
203                                         getQualifiedName() + ": Container does not have a provided interface named '" 
204                                         + aExternalProvided + "'");
205                 }
206         }
207         _edgeFilter.add(new ConnectExternalProvidedProvidedFilter(aExternalProvided, aComponent, aProvidedInterface));
208     }
209
210
211     @Override
212     public Container addProvidedInterface(ProvidedInterface aProvided) {
213         checkSealed();
214         super.addProvidedInterface(aProvided);
215         return this;
216     }
217
218     @Override
219     public Container addRequiredInterface(RequiredInterface aRequired) {
220         checkSealed();
221         super.addRequiredInterface(aRequired);
222         return this;
223     }
224
225     @Override
226     public void addContext(String aContext) {
227         super.addContext(aContext);
228         for (Component component : _components) {
229             component.addContext(aContext);
230         }
231     }
232
233     /**
234      * Validates the components together to check that there are no required
235      * services not in the required list and no services in the provided list
236      * that cannot be provided. Also logs a warning in case of superfluous
237      * requirements.
238      * 
239      * @throws SystemAssemblyException
240      *             in case of any validation problems.
241      */
242     public void validate() {
243         doStartOptionalDryRun(null, true);
244     }
245
246     /**
247      * Seal the container, meaning that no further components or interfaces may
248      * be added.
249      */
250     public void seal() {
251         _sealed = true;
252     }
253
254     /**
255      * Checks if the container is sealed.
256      * 
257      * @return True iff the container is sealed.
258      */
259     public boolean isSealed() {
260         return _sealed;
261     }
262
263     /**
264      * Utility method to start with an empty external scope. This is useful for
265      * top-level containers which are not part of another container.
266      * 
267      * @return Scope.
268      */
269     public Scope start() {
270         Scope scope = new DefaultScope(getProvidedInterfaces());
271         return super.start(scope);
272     }
273
274     @Override
275     protected Scope doStart(Scope aExternalScope) {
276         checkSealed();
277         validate();
278         Scope scope = new DefaultScope(getProvidedInterfaces().toArray(new ProvidedInterface[0]), aExternalScope);
279         ComponentGraph graph = doStartOptionalDryRun(scope, false);
280         exposeProvidedInterfaces(graph, aExternalScope, scope);
281         seal();
282         return scope;
283     }
284
285     private void exposeProvidedInterfaces(ComponentGraph aGraph, Scope aExternalScope,
286             Scope aInternalScope) {
287         for (Pair<ProvidedInterface,ProvidedInterface> mapping: 
288             aGraph.findExternalProvidedInterfaceMapping()) { 
289             Object svc = aInternalScope.getInterfaceImplementation(mapping.getSecond(), Object.class);
290             addInterface(mapping.getFirst(), svc, aExternalScope);
291         }
292     }
293
294     private ComponentGraph doStartOptionalDryRun(Scope aScope, boolean aDryRun) {
295         ComponentGraph graph = createComponentGraph();
296         graph.validate();
297         if (!aDryRun) {
298             graph.link();
299         }
300
301         LOG.info("Starting '" + getQualifiedName() + "'");
302
303         List<Component> started = new ArrayList<Component>();
304         for (Component component : _components) {
305             try {
306                 // Start the service.
307                 if (!aDryRun) {
308                     Object runtime = component.start(aScope);
309                     aScope.addRuntime(component, runtime);
310                     started.add(component);
311                 }
312             } catch (SystemAssemblyException e) {
313                 throw e;
314             } catch (RuntimeException e) {
315                 LOG.error(getQualifiedName() + ": could not start '"
316                         + component.getQualifiedName() + "'", e);
317                 stopAlreadyStartedComponents(started, aScope);
318                 throw e;
319             }
320         }
321         return graph;
322     }
323
324     private ComponentGraph createComponentGraph() {
325         ComponentGraph graph = new ComponentGraph();
326         for (RequiredInterface req : getRequiredInterfaces()) {
327             graph.addRequiredInterface(this, req);
328         }
329         for (Component comp : _components) {
330             graph.addComponent(comp);
331         }
332         for (ProvidedInterface prov: getProvidedInterfaces()) { 
333             graph.addProvidedInterface(this, prov);
334         }
335
336         graph.addEdgeFilter(_edgeFilter);
337         return graph;
338     }
339
340     private void stopAlreadyStartedComponents(List<Component> aStarted,
341             Scope aScope) {
342         // an exception occurred, stop the successfully started
343         // components
344         for (int i = aStarted.size() - 1; i >= 0; i--) {
345             try {
346                 Component component = aStarted.get(i);
347                 aStarted.get(i).stop(aScope.getRuntime(component));
348             } catch (Throwable t) {
349                 LOG.error(getQualifiedName() + ": error stopping "
350                         + aStarted.get(i).getQualifiedName());
351             }
352         }
353     }
354
355     @Override
356     protected void doStop(Scope aScope) {
357         for (int i = _components.size() - 1; i >= 0; i--) {
358             Component component = _components.get(i);
359             Object runtime = aScope.getRuntime(component);
360             component.stop(runtime);
361         }
362     }
363
364     private void checkSealed() {
365         if (_sealed) {
366             throw new SystemAssemblyException("Container is sealed");
367         }
368     }
369     
370     /**
371      * Finds a component based on the non-qualified name of the component. 
372      * @param aName Component name. 
373      * @return Component or null if not found. 
374      */
375     public Component findComponent(String aName) { 
376         for (Component<?> component: _components) { 
377                 if ( component.getName().equals(aName)) { 
378                         return component; 
379                 }
380         }
381         return null; 
382     }
383     
384     private static <T extends NamedInterface> T findInterface(List<T> aInterfaces, String aInterfaceName) { 
385         for (T intf: aInterfaces) { 
386                 if ( intf.getName().equals(aInterfaceName)) { 
387                         return intf; 
388                 }
389         }
390         return null; 
391     }
392 }