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