b44ca94f9b8512a0fdd3d30092bc314d1a32f567
[utils] / system / general / src / main / java / org / wamblee / system / core / 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.core;
17
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.HashSet;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Set;
25
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28
29 /**
30  * Container consisting of multiple components.
31  * 
32  * @author Erik Brakkee
33  */
34 public class Container extends AbstractComponent<Scope> {
35
36     private static final Log LOG = LogFactory.getLog(Container.class);
37
38     private List<Component> _components;
39     private Set<String> _componentNames;
40     private boolean _sealed;
41
42     public static RequiredInterface[] filterRequiredServices(
43             ProvidedInterface aProvided,
44             Collection<RequiredInterface> aDescriptors) {
45         List<RequiredInterface> required = new ArrayList<RequiredInterface>();
46         for (RequiredInterface descriptor : aDescriptors) {
47             if (descriptor.implementedBy(aProvided)) {
48                 required.add(descriptor);
49             }
50         }
51         return required.toArray(new RequiredInterface[0]);
52     }
53
54     public static ProvidedInterface[] filterProvidedServices(
55             RequiredInterface aRequired, Collection<ProvidedInterface> aProvided) {
56         List<ProvidedInterface> provided = new ArrayList<ProvidedInterface>();
57         for (ProvidedInterface descriptor : aProvided) {
58             if (aRequired.implementedBy(descriptor)) {
59                 provided.add(descriptor);
60             }
61         }
62         return provided.toArray(new ProvidedInterface[0]);
63     }
64
65     /**
66      * Constructs the container
67      * 
68      * @param aName
69      *            Name of the container
70      * @param aComponents
71      *            Components.
72      * @param aProvided
73      *            Provided services of the container
74      * @param aRequired
75      *            Required services by the container.
76      */
77     public Container(String aName, Component[] aComponents,
78             ProvidedInterface[] aProvided, RequiredInterface[] aRequired) {
79         super(aName, aProvided, aRequired);
80         _components = new ArrayList<Component>();
81
82         _componentNames = new HashSet<String>();
83         _sealed = false;
84         for (Component component : aComponents) {
85             addComponent(component);
86         }
87     }
88
89     public Container(String aName) {
90         this(aName, new Component[0], new ProvidedInterface[0],
91                 new RequiredInterface[0]);
92     }
93
94     public Container addComponent(Component aComponent) {
95         checkSealed();
96         if (aComponent.getContext() != null) {
97             throw new SystemAssemblyException(
98                     "Inconsistent hierarchy, component '"
99                             + aComponent.getName()
100                             + "' is already part of another hierarchy");
101         }
102         if (_componentNames.contains(aComponent.getName())) {
103             throw new SystemAssemblyException("Duplicate component '"
104                     + aComponent.getName() + "'");
105         }
106         _components.add(aComponent);
107         _componentNames.add(aComponent.getName());
108         aComponent.addContext(getQualifiedName());
109         return this;
110     }
111
112     @Override
113     public Container addProvidedInterface(ProvidedInterface aProvided) {
114         checkSealed();
115         super.addProvidedInterface(aProvided);
116         return this;
117     }
118
119     @Override
120     public Container addRequiredInterface(RequiredInterface aRequired) {
121         checkSealed();
122         super.addRequiredInterface(aRequired);
123         return this;
124     }
125
126     /**
127      * Validates the components together to check that there are no required
128      * services not in the required list and no services in the provided list
129      * that cannot be provided. Also logs a warning in case of superfluous
130      * requirements.
131      * 
132      * @throws SystemAssemblyException
133      *             in case of any validation problems.
134      */
135     public void validate() {
136         List<ProvidedInterface> provided = new ArrayList<ProvidedInterface>();
137         for (Component component : _components) {
138             provided.addAll(Arrays.asList(component.getProvidedInterfaces()));
139         }
140
141         List<RequiredInterface> required = new ArrayList<RequiredInterface>();
142         for (Component component : _components) {
143             required.addAll(Arrays.asList(component.getRequiredInterfaces()));
144         }
145
146         validateProvidedInterfacesArePresent(provided);
147
148         validateRequiredInterfaces(required);
149
150         doStartOptionalDryRun(null, true);
151     }
152
153     private void validateRequiredInterfaces(List<RequiredInterface> aRequired) {
154         for (RequiredInterface service : getRequiredInterfaces()) {
155             // TODO required interfaces by the component could be
156             // subclasses or implementations of the requirements
157             // of the contained components. The code below assumes
158             // an exact match.
159             if (!(aRequired.contains(service))) {
160                 info("Service '"
161                         + service
162                         + "' indicated as required is not actually required by any of the components");
163             }
164             // Check for the case that the externally required service
165             // is optional whereas the internally required service is
166             // mandatory.
167             if (service.isOptional()) {
168                 for (RequiredInterface intf : aRequired) {
169                     if (intf.equals(service) && !intf.isOptional()) {
170                         warn("Required service '"
171                                 + service
172                                 + "' indicated as optional is mandatory by one of its components ("
173                                 + getClients(intf)
174                                 + ", "
175                                 + intf
176                                 + "), this can lead to problems when the container is started and the interface is not provided to the container.");
177                     }
178                 }
179             }
180         }
181     }
182
183     private void validateProvidedInterfacesArePresent(
184             List<ProvidedInterface> aProvided) {
185         for (ProvidedInterface service : getProvidedInterfaces()) {
186             // TODO provided interfaces by components could be
187             // provide subclasses or implementations of the
188             // provided interfaces of the container.
189             // The code below assumes an exact match.
190             if (!(aProvided.contains(service))) {
191                 throw new SystemAssemblyException(getName() + ": Service '"
192                         + service
193                         + "' is not provided by any of its components");
194             }
195         }
196     }
197
198     /**
199      * Starts the container. After the container is started, the container
200      * becomes sealed meaning that no further components, required or provided
201      * interfaces may be added.
202      * 
203      * @return Scope.
204      */
205     public Scope start() {
206         checkSealed();
207         validate();
208         Scope scope = super.start(new DefaultScope(new ProvidedInterface[0]));
209         seal();
210         return scope;
211     }
212
213     /**
214      * Seal the container, meaning that no further components or interfaces may
215      * be added.
216      */
217     public void seal() {
218         _sealed = true;
219     }
220
221     /**
222      * Checks if the container is sealed.
223      * 
224      * @return True iff the container is sealed.
225      */
226     public boolean isSealed() {
227         return _sealed;
228     }
229
230     @Override
231     protected Scope doStart(Scope aExternalScope) {
232         return doStartOptionalDryRun(aExternalScope, false);
233     }
234
235     private Scope doStartOptionalDryRun(Scope aExternalScope, boolean aDryRun) {
236         LOG.info("Starting '" + getQualifiedName() + "'");
237
238         Scope scope = new DefaultScope(getProvidedInterfaces(), aExternalScope);
239
240         List<ProvidedInterface> allProvided = new ArrayList<ProvidedInterface>();
241
242         addProvidersOfRequiredInterfaces(allProvided);
243
244         List<Component> started = new ArrayList<Component>();
245         for (Component component : _components) {
246             try {
247                 initializeProvidersForRequiredInterfaces(allProvided,
248                         component, aDryRun);
249
250                 // Start the service.
251                 if (!aDryRun) {
252                     Object runtime = component.start(scope);
253                     scope.addRuntime(component, runtime);
254                     started.add(component);
255                 }
256
257                 // add all provided services
258                 ProvidedInterface[] provided = component
259                         .getProvidedInterfaces();
260                 allProvided.addAll(Arrays.asList(provided));
261             } catch (SystemAssemblyException e) {
262                 throw e;
263             } catch (RuntimeException e) {
264                 LOG.error(getQualifiedName() + ": could not start '"
265                         + component.getQualifiedName() + "'", e);
266                 stopAlreadyStartedComponents(started, scope);
267                 throw e;
268             }
269         }
270         return scope;
271     }
272
273     private void addProvidersOfRequiredInterfaces(
274             List<ProvidedInterface> allProvided) {
275         // all interfaces from the required list of this container are
276         // provided to the components inside it.
277         RequiredInterface[] required = getRequiredInterfaces();
278         for (RequiredInterface intf : required) {
279             ProvidedInterface provider = intf.getProvider();
280             if (provider != null) {
281                 allProvided.add(provider);
282             } else {
283                 if (!intf.isOptional()) {
284                     throw new SystemAssemblyException(getQualifiedName()
285                             + ": required interface '" + intf
286                             + "' is not provided");
287                 }
288             }
289         }
290     }
291
292     private void stopAlreadyStartedComponents(List<Component> aStarted,
293             Scope aScope) {
294         // an exception occurred, stop the successfully started
295         // components
296         for (int i = aStarted.size() - 1; i >= 0; i--) {
297             try {
298                 Component component = aStarted.get(i);
299                 aStarted.get(i).stop(aScope.getRuntime(component));
300             } catch (Throwable t) {
301                 LOG.error(getQualifiedName() + ": error stopping "
302                         + aStarted.get(i).getQualifiedName());
303             }
304         }
305     }
306
307     /**
308      * Sets the provided interface or a component.
309      * 
310      * @param aAllProvided
311      *            All available provided interfaces.
312      * @param aComponent
313      *            Component whose required interfaces we are looking at.
314      * @param aValidateOnly
315      *            If true then the provider will not be set for required
316      *            interfaces.
317      */
318     private void initializeProvidersForRequiredInterfaces(
319             List<ProvidedInterface> aAllProvided, Component aComponent,
320             boolean aValidateOnly) {
321         // Check if all required services are already provided by
322         // earlier
323         // systems.
324
325         for (RequiredInterface descriptor : aComponent.getRequiredInterfaces()) {
326             ProvidedInterface[] filtered = filterProvidedServices(descriptor,
327                     aAllProvided);
328             if (filtered.length == 1) {
329                 if (!aValidateOnly) {
330                     descriptor.setProvider(filtered[0]);
331                 }
332             } else if (filtered.length > 1) {
333                 throw new SystemAssemblyException(
334                         "Service '"
335                                 + descriptor
336                                 + "' required by system '"
337                                 + aComponent
338                                 + "' matches multiple services provided by other systems: "
339                                 + getServers(filtered));
340             } else {
341                 // filtered.length == 0
342                 if (!descriptor.isOptional()) {
343                     throw new SystemAssemblyException(
344                             "Service '"
345                                     + descriptor
346                                     + "' required by system '"
347                                     + aComponent
348                                     + "' is not provided by systems that are started earlier");
349                 }
350             }
351         }
352     }
353
354     @Override
355     protected void doStop(Scope aScope) {
356         for (int i = _components.size() - 1; i >= 0; i--) {
357             Component component = _components.get(i);
358             Object runtime = aScope.getRuntime(component);
359             component.stop(runtime);
360         }
361     }
362
363     private void info(String aMsg) {
364         LOG.info(getQualifiedName() + ": " + aMsg);
365     }
366
367     private void warn(String aMsg) {
368         LOG.warn(getQualifiedName() + ": " + aMsg);
369     }
370
371     private String getServers(ProvidedInterface[] aProvidedList) {
372         String result = "";
373         for (ProvidedInterface provided : aProvidedList) {
374             result += "(components ";
375             for (Component component : _components) {
376                 for (ProvidedInterface provided2 : component
377                         .getProvidedInterfaces()) {
378                     if (provided.equals(provided2)) {
379                         result += component + " ";
380                     }
381                 }
382             }
383             result += ", interface " + provided + ")";
384         }
385         return result;
386     }
387
388     private List<Component> getClients(RequiredInterface aRequirement) {
389         List<Component> clients = new ArrayList<Component>();
390         for (Component component : _components) {
391             for (RequiredInterface required : component.getRequiredInterfaces()) {
392                 if (required.equals(aRequirement)
393                         && required.isOptional() == aRequirement.isOptional()) {
394                     clients.add(component);
395                 }
396             }
397         }
398         return clients;
399     }
400
401     private void checkSealed() {
402         if (_sealed) {
403             throw new SystemAssemblyException("Container is sealed");
404         }
405     }
406 }