(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.HashSet;
20 import java.util.List;
21 import java.util.Set;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.wamblee.general.Pair;
26 import org.wamblee.system.core.AbstractComponent;
27 import org.wamblee.system.core.Component;
28 import org.wamblee.system.core.DefaultScope;
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.component.ComponentGraph;
34
35 /**
36  * Container consisting of multiple components.
37  * 
38  * @author Erik Brakkee
39  */
40 public class Container extends AbstractComponent<Scope> {
41
42     private static final Log LOG = LogFactory.getLog(Container.class);
43
44     private List<Component> _components;
45     private Set<String> _componentNames;
46     private CompositeInterfaceRestriction _restriction;
47     private boolean _sealed;
48
49     /**
50      * Constructs the container
51      * 
52      * @param aName
53      *            Name of the container
54      * @param aComponents
55      *            Components.
56      * @param aProvided
57      *            Provided services of the container
58      * @param aRequired
59      *            Required services by the container.
60      */
61     public Container(String aName, Component[] aComponents,
62             ProvidedInterface[] aProvided, RequiredInterface[] aRequired) {
63         super(aName, aProvided, aRequired);
64         _components = new ArrayList<Component>();
65
66         _componentNames = new HashSet<String>();
67         _restriction = new CompositeInterfaceRestriction();
68         _sealed = false;
69         for (Component component : aComponents) {
70             addComponent(component);
71         }
72     }
73
74     public Container(String aName) {
75         this(aName, new Component[0], new ProvidedInterface[0],
76                 new RequiredInterface[0]);
77     }
78
79     public Container addComponent(Component aComponent) {
80         checkSealed();
81         if (aComponent.getContext() != null) {
82             throw new SystemAssemblyException(
83                     "Inconsistent hierarchy, component '"
84                             + aComponent.getName()
85                             + "' is already part of another hierarchy");
86         }
87         if (_componentNames.contains(aComponent.getName())) {
88             throw new SystemAssemblyException("Duplicate component '"
89                     + aComponent.getName() + "'");
90         }
91         _components.add(aComponent);
92         _componentNames.add(aComponent.getName());
93         aComponent.addContext(getQualifiedName());
94         return this;
95     }
96
97     /**
98      * Adds an interface restriction for explicitly configuring the relations
99      * between components.
100      * 
101      * @param aRestriction
102      *            Restriction to add.
103      * @return Reference to this to allow call chaining.
104      */
105     public Container addRestriction(InterfaceRestriction aRestriction) {
106         checkSealed();
107         _restriction.add(aRestriction);
108         return this;
109     }
110
111     @Override
112     public Container addProvidedInterface(ProvidedInterface aProvided) {
113         checkSealed();
114         super.addProvidedInterface(aProvided);
115         return this;
116     }
117
118     @Override
119     public Container addRequiredInterface(RequiredInterface aRequired) {
120         checkSealed();
121         super.addRequiredInterface(aRequired);
122         return this;
123     }
124
125     @Override
126     public void addContext(String aContext) {
127         super.addContext(aContext);
128         for (Component component : _components) {
129             component.addContext(aContext);
130         }
131     }
132
133     /**
134      * Validates the components together to check that there are no required
135      * services not in the required list and no services in the provided list
136      * that cannot be provided. Also logs a warning in case of superfluous
137      * requirements.
138      * 
139      * @throws SystemAssemblyException
140      *             in case of any validation problems.
141      */
142     public void validate() {
143         doStartOptionalDryRun(null, true);
144     }
145
146     /**
147      * Seal the container, meaning that no further components or interfaces may
148      * be added.
149      */
150     public void seal() {
151         _sealed = true;
152     }
153
154     /**
155      * Checks if the container is sealed.
156      * 
157      * @return True iff the container is sealed.
158      */
159     public boolean isSealed() {
160         return _sealed;
161     }
162
163     /**
164      * Utility method to start with an empty external scope. This is useful for
165      * top-level containers which are not part of another container.
166      * 
167      * @return Scope.
168      */
169     public Scope start() {
170         Scope scope = new DefaultScope(getProvidedInterfaces());
171         return super.start(scope);
172     }
173
174     @Override
175     protected Scope doStart(Scope aExternalScope) {
176         checkSealed();
177         validate();
178         Scope scope = new DefaultScope(getProvidedInterfaces(), aExternalScope);
179         ComponentGraph graph = doStartOptionalDryRun(scope, false);
180         exposeProvidedInterfaces(graph, aExternalScope, scope);
181         seal();
182         return scope;
183     }
184
185     private void exposeProvidedInterfaces(ComponentGraph aGraph, Scope aExternalScope,
186             Scope aInternalScope) {
187         for (Pair<ProvidedInterface,ProvidedInterface> mapping: 
188             aGraph.findExternalProvidedInterfaceMapping()) { 
189             Object svc = aInternalScope.getInterfaceImplementation(mapping.getSecond(), Object.class);
190             addInterface(mapping.getFirst(), svc, aExternalScope);
191         }
192     }
193
194     private ComponentGraph doStartOptionalDryRun(Scope aScope, boolean aDryRun) {
195         ComponentGraph graph = createComponentGraph();
196         graph.validate();
197         if (!aDryRun) {
198             graph.link();
199         }
200
201         LOG.info("Starting '" + getQualifiedName() + "'");
202
203         List<Component> started = new ArrayList<Component>();
204         for (Component component : _components) {
205             try {
206                 // Start the service.
207                 if (!aDryRun) {
208                     Object runtime = component.start(aScope);
209                     aScope.addRuntime(component, runtime);
210                     started.add(component);
211                 }
212             } catch (SystemAssemblyException e) {
213                 throw e;
214             } catch (RuntimeException e) {
215                 LOG.error(getQualifiedName() + ": could not start '"
216                         + component.getQualifiedName() + "'", e);
217                 stopAlreadyStartedComponents(started, aScope);
218                 throw e;
219             }
220         }
221         return graph;
222     }
223
224     private ComponentGraph createComponentGraph() {
225         ComponentGraph graph = new ComponentGraph();
226         for (RequiredInterface req : getRequiredInterfaces()) {
227             graph.addRequiredInterface(this, req);
228         }
229         for (Component comp : _components) {
230             graph.addComponent(comp);
231         }
232         for (ProvidedInterface prov: getProvidedInterfaces()) { 
233             graph.addProvidedInterface(this, prov);
234         }
235
236         graph.addRestriction(_restriction);
237         return graph;
238     }
239
240     private void stopAlreadyStartedComponents(List<Component> aStarted,
241             Scope aScope) {
242         // an exception occurred, stop the successfully started
243         // components
244         for (int i = aStarted.size() - 1; i >= 0; i--) {
245             try {
246                 Component component = aStarted.get(i);
247                 aStarted.get(i).stop(aScope.getRuntime(component));
248             } catch (Throwable t) {
249                 LOG.error(getQualifiedName() + ": error stopping "
250                         + aStarted.get(i).getQualifiedName());
251             }
252         }
253     }
254
255     @Override
256     protected void doStop(Scope aScope) {
257         for (int i = _components.size() - 1; i >= 0; i--) {
258             Component component = _components.get(i);
259             Object runtime = aScope.getRuntime(component);
260             component.stop(runtime);
261         }
262     }
263
264     private void checkSealed() {
265         if (_sealed) {
266             throw new SystemAssemblyException("Container is sealed");
267         }
268     }
269 }