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