(no commit message)
[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         validateProvidedInterfacesArePresent();
137
138         validateRequiredInterfaces();
139
140         doStartOptionalDryRun(null, true);
141     }
142
143     private void validateRequiredInterfaces() {
144         List<RequiredInterface> required = new ArrayList<RequiredInterface>();
145         for (Component component : _components) {
146             required.addAll(Arrays.asList(component.getRequiredInterfaces()));
147         }
148
149         for (RequiredInterface service : getRequiredInterfaces()) {
150             // TODO required interfaces by the component could be
151             // subclasses or implementations of the requirements
152             // of the contained components. The code below assumes
153             // an exact match.
154             if (!(required.contains(service))) {
155                 info("Service '"
156                         + service
157                         + "' indicated as required is not actually required by any of the components");
158             }
159             // Check for the case that the externally required service
160             // is optional whereas the internally required service is
161             // mandatory.
162             if (service.isOptional()) {
163                 for (RequiredInterface intf : required) {
164                     if (intf.equals(service) && !intf.isOptional()) {
165                         warn("Required service '"
166                                 + service
167                                 + "' indicated as optional is mandatory by one of its components ("
168                                 + getClients(intf)
169                                 + ", "
170                                 + intf
171                                 + "), this can lead to problems when the container is started and the interface is not provided to the container.");
172                     }
173                 }
174             }
175         }
176     }
177
178     private void validateProvidedInterfacesArePresent() {
179         List<ProvidedInterface> provided = new ArrayList<ProvidedInterface>();
180         for (Component component : _components) {
181             provided.addAll(Arrays.asList(component.getProvidedInterfaces()));
182         }
183         for (ProvidedInterface service : getProvidedInterfaces()) {
184             // TODO provided interfaces by components could be
185             // provide subclasses or implementations of the
186             // provided interfaces of the container.
187             // The code below assumes an exact match.
188             if (!(provided.contains(service))) {
189                 throw new SystemAssemblyException(getName() + ": Service '"
190                         + service
191                         + "' is not provided by any of its components");
192             }
193         }
194     }
195
196     /**
197      * Starts the container. After the container is started, the container
198      * becomes sealed meaning that no further components, required or provided
199      * interfaces may be added.
200      * 
201      * @return Scope.
202      */
203     public Scope start() {
204         checkSealed();
205         validate();
206         Scope scope = super.start(new DefaultScope(new ProvidedInterface[0]));
207         seal();
208         return scope;
209     }
210
211     /**
212      * Seal the container, meaning that no further components or interfaces may
213      * be added.
214      */
215     public void seal() {
216         _sealed = true;
217     }
218
219     /**
220      * Checks if the container is sealed.
221      * 
222      * @return True iff the container is sealed.
223      */
224     public boolean isSealed() {
225         return _sealed;
226     }
227
228     @Override
229     protected Scope doStart(Scope aExternalScope) {
230         return doStartOptionalDryRun(aExternalScope, false);
231     }
232
233     private Scope doStartOptionalDryRun(Scope aExternalScope, boolean aDryRun) {
234         LOG.info("Starting '" + getQualifiedName() + "'");
235
236         Scope scope = new DefaultScope(getProvidedInterfaces(), aExternalScope);
237
238         List<ProvidedInterface> allProvided = new ArrayList<ProvidedInterface>();
239
240         addProvidersOfRequiredInterfaces(allProvided);
241
242         List<Component> started = new ArrayList<Component>();
243         for (Component component : _components) {
244             try {
245                 initializeProvidersForRequiredInterfaces(allProvided,
246                         component, aDryRun);
247
248                 // Start the service.
249                 if (!aDryRun) {
250                     Object runtime = component.start(scope);
251                     scope.addRuntime(component, runtime);
252                     started.add(component);
253                 }
254
255                 // add all provided services
256                 ProvidedInterface[] provided = component
257                         .getProvidedInterfaces();
258                 allProvided.addAll(Arrays.asList(provided));
259             } catch (SystemAssemblyException e) {
260                 throw e;
261             } catch (RuntimeException e) {
262                 LOG.error(getQualifiedName() + ": could not start '"
263                         + component.getQualifiedName() + "'", e);
264                 stopAlreadyStartedComponents(started, scope);
265                 throw e;
266             }
267         }
268         return scope;
269     }
270
271     private void addProvidersOfRequiredInterfaces(
272             List<ProvidedInterface> allProvided) {
273         // all interfaces from the required list of this container are
274         // provided to the components inside it.
275         RequiredInterface[] required = getRequiredInterfaces();
276         for (RequiredInterface intf : required) {
277             ProvidedInterface provider = intf.getProvider();
278             if (provider != null) {
279                 allProvided.add(provider);
280             } else {
281                 if (!intf.isOptional()) {
282                     throw new SystemAssemblyException(getQualifiedName()
283                             + ": required interface '" + intf
284                             + "' is not provided");
285                 }
286             }
287         }
288     }
289
290     private void stopAlreadyStartedComponents(List<Component> aStarted,
291             Scope aScope) {
292         // an exception occurred, stop the successfully started
293         // components
294         for (int i = aStarted.size() - 1; i >= 0; i--) {
295             try {
296                 Component component = aStarted.get(i);
297                 aStarted.get(i).stop(aScope.getRuntime(component));
298             } catch (Throwable t) {
299                 LOG.error(getQualifiedName() + ": error stopping "
300                         + aStarted.get(i).getQualifiedName());
301             }
302         }
303     }
304
305     /**
306      * Sets the provided interface or a component.
307      * 
308      * @param aAllProvided
309      *            All available provided interfaces.
310      * @param aComponent
311      *            Component whose required interfaces we are looking at.
312      * @param aValidateOnly
313      *            If true then the provider will not be set for required
314      *            interfaces.
315      */
316     private void initializeProvidersForRequiredInterfaces(
317             List<ProvidedInterface> aAllProvided, Component aComponent,
318             boolean aValidateOnly) {
319         // Check if all required services are already provided by
320         // earlier
321         // systems.
322
323         for (RequiredInterface descriptor : aComponent.getRequiredInterfaces()) {
324             ProvidedInterface[] filtered = filterProvidedServices(descriptor,
325                     aAllProvided);
326             if (filtered.length == 1) {
327                 if (!aValidateOnly) {
328                     descriptor.setProvider(filtered[0]);
329                 }
330             } else if (filtered.length > 1) {
331                 throw new SystemAssemblyException(
332                         "Service '"
333                                 + descriptor
334                                 + "' required by system '"
335                                 + aComponent
336                                 + "' matches multiple services provided by other systems: "
337                                 + getServers(filtered));
338             } else {
339                 // filtered.length == 0
340                 if (!descriptor.isOptional()) {
341                     throw new SystemAssemblyException(
342                             "Service '"
343                                     + descriptor
344                                     + "' required by system '"
345                                     + aComponent
346                                     + "' is not provided by systems that are started earlier");
347                 }
348             }
349         }
350     }
351
352     @Override
353     protected void doStop(Scope aScope) {
354         for (int i = _components.size() - 1; i >= 0; i--) {
355             Component component = _components.get(i);
356             Object runtime = aScope.getRuntime(component);
357             component.stop(runtime);
358         }
359     }
360
361     private void info(String aMsg) {
362         LOG.info(getQualifiedName() + ": " + aMsg);
363     }
364
365     private void warn(String aMsg) {
366         LOG.warn(getQualifiedName() + ": " + aMsg);
367     }
368
369     private String getServers(ProvidedInterface[] aProvidedList) {
370         String result = "";
371         for (ProvidedInterface provided : aProvidedList) {
372             result += "(components ";
373             for (Component component : _components) {
374                 for (ProvidedInterface provided2 : component
375                         .getProvidedInterfaces()) {
376                     if (provided.equals(provided2)) {
377                         result += component + " ";
378                     }
379                 }
380             }
381             result += ", interface " + provided + ")";
382         }
383         return result;
384     }
385
386     private List<Component> getClients(RequiredInterface aRequirement) {
387         List<Component> clients = new ArrayList<Component>();
388         for (Component component : _components) {
389             for (RequiredInterface required : component.getRequiredInterfaces()) {
390                 if (required.equals(aRequirement)
391                         && required.isOptional() == aRequirement.isOptional()) {
392                     clients.add(component);
393                 }
394             }
395         }
396         return clients;
397     }
398
399     private void checkSealed() {
400         if (_sealed) {
401             throw new SystemAssemblyException("Container is sealed");
402         }
403     }
404 }