(no commit message)
[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         // TODO validate
164         _edgeFilter.add(new ConnectRequiredExternallyRequiredEdgeFilter(
165                 aComponent, aRequiredInterface, aExternalRequiredInterface));
166     }
167     
168     public void connectExternalProvided(String aExternalProvided, String aComponent, String aProvidedInterface) {
169         checkSealed();
170         // TODO validate
171         _edgeFilter.add(new ConnectExternalProvidedProvidedFilter(aExternalProvided, aComponent, aProvidedInterface));
172     }
173
174
175     @Override
176     public Container addProvidedInterface(ProvidedInterface aProvided) {
177         checkSealed();
178         super.addProvidedInterface(aProvided);
179         return this;
180     }
181
182     @Override
183     public Container addRequiredInterface(RequiredInterface aRequired) {
184         checkSealed();
185         super.addRequiredInterface(aRequired);
186         return this;
187     }
188
189     @Override
190     public void addContext(String aContext) {
191         super.addContext(aContext);
192         for (Component component : _components) {
193             component.addContext(aContext);
194         }
195     }
196
197     /**
198      * Validates the components together to check that there are no required
199      * services not in the required list and no services in the provided list
200      * that cannot be provided. Also logs a warning in case of superfluous
201      * requirements.
202      * 
203      * @throws SystemAssemblyException
204      *             in case of any validation problems.
205      */
206     public void validate() {
207         doStartOptionalDryRun(null, true);
208     }
209
210     /**
211      * Seal the container, meaning that no further components or interfaces may
212      * be added.
213      */
214     public void seal() {
215         _sealed = true;
216     }
217
218     /**
219      * Checks if the container is sealed.
220      * 
221      * @return True iff the container is sealed.
222      */
223     public boolean isSealed() {
224         return _sealed;
225     }
226
227     /**
228      * Utility method to start with an empty external scope. This is useful for
229      * top-level containers which are not part of another container.
230      * 
231      * @return Scope.
232      */
233     public Scope start() {
234         Scope scope = new DefaultScope(getProvidedInterfaces());
235         return super.start(scope);
236     }
237
238     @Override
239     protected Scope doStart(Scope aExternalScope) {
240         checkSealed();
241         validate();
242         Scope scope = new DefaultScope(getProvidedInterfaces().toArray(new ProvidedInterface[0]), aExternalScope);
243         ComponentGraph graph = doStartOptionalDryRun(scope, false);
244         exposeProvidedInterfaces(graph, aExternalScope, scope);
245         seal();
246         return scope;
247     }
248
249     private void exposeProvidedInterfaces(ComponentGraph aGraph, Scope aExternalScope,
250             Scope aInternalScope) {
251         for (Pair<ProvidedInterface,ProvidedInterface> mapping: 
252             aGraph.findExternalProvidedInterfaceMapping()) { 
253             Object svc = aInternalScope.getInterfaceImplementation(mapping.getSecond(), Object.class);
254             addInterface(mapping.getFirst(), svc, aExternalScope);
255         }
256     }
257
258     private ComponentGraph doStartOptionalDryRun(Scope aScope, boolean aDryRun) {
259         ComponentGraph graph = createComponentGraph();
260         graph.validate();
261         if (!aDryRun) {
262             graph.link();
263         }
264
265         LOG.info("Starting '" + getQualifiedName() + "'");
266
267         List<Component> started = new ArrayList<Component>();
268         for (Component component : _components) {
269             try {
270                 // Start the service.
271                 if (!aDryRun) {
272                     Object runtime = component.start(aScope);
273                     aScope.addRuntime(component, runtime);
274                     started.add(component);
275                 }
276             } catch (SystemAssemblyException e) {
277                 throw e;
278             } catch (RuntimeException e) {
279                 LOG.error(getQualifiedName() + ": could not start '"
280                         + component.getQualifiedName() + "'", e);
281                 stopAlreadyStartedComponents(started, aScope);
282                 throw e;
283             }
284         }
285         return graph;
286     }
287
288     private ComponentGraph createComponentGraph() {
289         ComponentGraph graph = new ComponentGraph();
290         for (RequiredInterface req : getRequiredInterfaces()) {
291             graph.addRequiredInterface(this, req);
292         }
293         for (Component comp : _components) {
294             graph.addComponent(comp);
295         }
296         for (ProvidedInterface prov: getProvidedInterfaces()) { 
297             graph.addProvidedInterface(this, prov);
298         }
299
300         graph.addEdgeFilter(_edgeFilter);
301         return graph;
302     }
303
304     private void stopAlreadyStartedComponents(List<Component> aStarted,
305             Scope aScope) {
306         // an exception occurred, stop the successfully started
307         // components
308         for (int i = aStarted.size() - 1; i >= 0; i--) {
309             try {
310                 Component component = aStarted.get(i);
311                 aStarted.get(i).stop(aScope.getRuntime(component));
312             } catch (Throwable t) {
313                 LOG.error(getQualifiedName() + ": error stopping "
314                         + aStarted.get(i).getQualifiedName());
315             }
316         }
317     }
318
319     @Override
320     protected void doStop(Scope aScope) {
321         for (int i = _components.size() - 1; i >= 0; i--) {
322             Component component = _components.get(i);
323             Object runtime = aScope.getRuntime(component);
324             component.stop(runtime);
325         }
326     }
327
328     private void checkSealed() {
329         if (_sealed) {
330             throw new SystemAssemblyException("Container is sealed");
331         }
332     }
333     
334     /**
335      * Finds a component based on the non-qualified name of the component. 
336      * @param aName Component name. 
337      * @return Component or null if not found. 
338      */
339     public Component findComponent(String aName) { 
340         for (Component<?> component: _components) { 
341                 if ( component.getName().equals(aName)) { 
342                         return component; 
343                 }
344         }
345         return null; 
346     }
347     
348     private static <T extends NamedInterface> T findInterface(List<T> aInterfaces, String aInterfaceName) { 
349         for (T intf: aInterfaces) { 
350                 if ( intf.getName().equals(aInterfaceName)) { 
351                         return intf; 
352                 }
353         }
354         return null; 
355     }
356 }