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