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