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