summaryrefslogtreecommitdiffstats
path: root/sandbox/rfeng/minicore/src/main/java/org/apache/tuscany/core/component/scope/AbstractScopeContainer.java
blob: 7fa876542667b0eba54e696c4ccd2f66eec4f60b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */
package org.apache.tuscany.core.component.scope;


import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.osoa.sca.annotations.Destroy;
import org.osoa.sca.annotations.Init;
import org.osoa.sca.annotations.Reference;

import org.apache.tuscany.spi.AbstractLifecycle;
import org.apache.tuscany.spi.component.AtomicComponent;
import org.apache.tuscany.spi.component.GroupInitializationException;
import org.apache.tuscany.spi.component.InstanceWrapper;
import org.apache.tuscany.spi.component.PersistenceException;
import org.apache.tuscany.spi.component.ScopeContainer;
import org.apache.tuscany.spi.component.ScopeContainerMonitor;
import org.apache.tuscany.spi.component.ScopeRegistry;
import org.apache.tuscany.spi.component.TargetDestructionException;
import org.apache.tuscany.spi.component.TargetResolutionException;
import org.apache.tuscany.spi.event.Event;
import org.apache.tuscany.spi.model.Scope;

/**
 * Implements functionality common to scope contexts.
 *
 * @version $Rev$ $Date$
 */
public abstract class AbstractScopeContainer<KEY> extends AbstractLifecycle
    implements ScopeContainer<KEY> {

    private static final Comparator<AtomicComponent<?>> COMPARATOR = new Comparator<AtomicComponent<?>>() {
        public int compare(AtomicComponent<?> o1, AtomicComponent<?> o2) {
            return o1.getInitLevel() - o2.getInitLevel();
        }
    };

    private final Scope scope;
    protected final ScopeContainerMonitor monitor;

    protected final Map<AtomicComponent<?>, URI> componentGroups =
        new ConcurrentHashMap<AtomicComponent<?>, URI>();

    protected final Map<KEY, URI> contextGroups = new ConcurrentHashMap<KEY, URI>();

    // the queue of components to eagerly initialize in each group
    protected final Map<URI, List<AtomicComponent<?>>> initQueues =
        new HashMap<URI, List<AtomicComponent<?>>>();

    // the queue of instanceWrappers to destroy, in the order that their instances were created
    protected final Map<KEY, List<InstanceWrapper<?>>> destroyQueues =
        new ConcurrentHashMap<KEY, List<InstanceWrapper<?>>>();

    public AbstractScopeContainer(Scope scope, ScopeContainerMonitor monitor) {
        this.scope = scope;
        this.monitor = monitor;
    }

    public Scope getScope() {
        return scope;
    }

    @Reference
    public void setScopeRegistry(ScopeRegistry scopeRegistry) {
        scopeRegistry.register(this);
    }

    @Init
    public synchronized void start() {
        int lifecycleState = getLifecycleState();
        if (lifecycleState != UNINITIALIZED && lifecycleState != STOPPED) {
            throw new IllegalStateException("Scope must be in UNINITIALIZED or STOPPED state [" + lifecycleState + "]");
        }
        setLifecycleState(RUNNING);
    }

    @Destroy
    public synchronized void stop() {
        int lifecycleState = getLifecycleState();
        if (lifecycleState != RUNNING) {
            throw new IllegalStateException("Scope in wrong state [" + lifecycleState + "]");
        }
        setLifecycleState(STOPPED);
        componentGroups.clear();
        contextGroups.clear();
        synchronized (initQueues) {
            initQueues.clear();
        }
        destroyQueues.clear();
    }

    protected void checkInit() {
        if (getLifecycleState() != RUNNING) {
            throw new IllegalStateException("Scope container not running [" + getLifecycleState() + "]");
        }
    }

    public void onEvent(Event event) {
    }

    public <T> void register(AtomicComponent<T> component, URI groupId) {
        checkInit();
        if (component.isEagerInit()) {
            componentGroups.put(component, groupId);
            synchronized (initQueues) {
                List<AtomicComponent<?>> initQueue = initQueues.get(groupId);
                if (initQueue == null) {
                    initQueue = new ArrayList<AtomicComponent<?>>();
                    initQueues.put(groupId, initQueue);
                }
                // FIXME it would be more efficient to binary search and then insert
                initQueue.add(component);
                Collections.sort(initQueue, COMPARATOR);
            }
        }
    }

    public <T> void unregister(AtomicComponent<T> component) {
        if (component.isEagerInit()) {
            URI groupId = componentGroups.remove(component);
            synchronized (initQueues) {
                List<AtomicComponent<?>> initQueue = initQueues.get(groupId);
                initQueue.remove(component);
                if (initQueue.isEmpty()) {
                    initQueues.remove(groupId);
                }
            }
        }
    }

    public void startContext(KEY contextId, URI groupId) throws GroupInitializationException {
        assert !contextGroups.containsKey(contextId);
        contextGroups.put(contextId, groupId);
        destroyQueues.put(contextId, new ArrayList<InstanceWrapper<?>>());

        // get and clone initialization queue
        List<AtomicComponent<?>> initQueue;
        synchronized (initQueues) {
            initQueue = initQueues.get(groupId);
            if (initQueue != null) {
                initQueue = new ArrayList<AtomicComponent<?>>(initQueue);
            }
        }
        if (initQueue != null) {
            initializeComponents(contextId, initQueue);
        }
    }

    public void stopContext(KEY contextId) {
        assert contextGroups.containsKey(contextId);
        shutdownComponents(destroyQueues.get(contextId));
        contextGroups.remove(contextId);
        destroyQueues.remove(contextId);
    }

    public <T> InstanceWrapper<T> getWrapper(AtomicComponent<T> component, KEY contextId)
        throws TargetResolutionException {
        return null;
    }

    public <T> InstanceWrapper<T> getAssociatedWrapper(AtomicComponent<T> component, KEY contextId)
        throws TargetResolutionException {
        return null;
    }

    public <T> void returnWrapper(AtomicComponent<T> component, InstanceWrapper<T> wrapper, KEY contextId)
        throws TargetDestructionException {
    }

    public <T> void remove(AtomicComponent<T> component) throws PersistenceException {
        throw new UnsupportedOperationException("Scope does not support persistence");
    }

    /**
     * Initialise an ordered list of components.
     * The list is traversed in order and the getWrapper() method called for each to
     * associate an instance with the supplied context.
     *
     * @param contextId  the contextId to associated with the component instances
     * @param components the components to be initialized
     * @throws GroupInitializationException if one or more components threw an exception during initialization
     */
    protected void initializeComponents(KEY contextId, List<AtomicComponent<?>> components)
        throws GroupInitializationException {
        List<Exception> causes = null;
        for (AtomicComponent<?> component : components) {
            try {
                getWrapper(component, contextId);

            } catch (Exception e) {
                if (causes == null) {
                    causes = new ArrayList<Exception>();
                }
                causes.add(e);
            }
        }
        if (causes != null) {
            throw new GroupInitializationException(String.valueOf(contextId), causes);
        }
    }

    /**
     * Shut down an ordered list of instances.
     * The list passed to this method is treated as a live, mutable list
     * so any instances added to this list as shutdown is occuring will also be shut down.
     *
     * @param instances the list of instances to shutdown
     */
    protected void shutdownComponents(List<InstanceWrapper<?>> instances) {
        while (true) {
            InstanceWrapper<?> toDestroy;
            synchronized (instances) {
                if (instances.size() == 0) {
                    return;
                }
                toDestroy = instances.remove(instances.size() - 1);
            }
            try {
                toDestroy.stop();
            } catch (TargetDestructionException e) {
                // log the error from destroy but continue
                monitor.destructionError(e);
            }
        }
    }

    public String toString() {
        return "In state [" + super.toString() + ']';
    }

    /**
     * Creates a new physical instance of a component, wrapped in an InstanceWrapper.
     *
     * @param component the component whose instance should be created
     * @return a wrapped instance that has been injected but not yet started
     * @throws TargetResolutionException if there was a problem creating the instance
     */
    protected <T> InstanceWrapper<T> createInstance(AtomicComponent<T> component) throws TargetResolutionException {
        return component.createInstanceWrapper();
    }
}