summaryrefslogtreecommitdiffstats
path: root/sandbox/rfeng/minicore/src/main/java/org/apache/tuscany/core/runtime/AbstractRuntime.java
blob: 4a9cbb1ff57f6f99750449e9fd2bfa1af886dbdd (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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/*
 * 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.runtime;

import static org.apache.tuscany.spi.bootstrap.ComponentNames.TUSCANY_DEPLOYER;
import static org.apache.tuscany.spi.bootstrap.ComponentNames.TUSCANY_SYSTEM;
import static org.apache.tuscany.spi.bootstrap.ComponentNames.TUSCANY_SYSTEM_ROOT;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.xml.stream.XMLInputFactory;

import org.apache.tuscany.core.bootstrap.Bootstrapper;
import org.apache.tuscany.core.bootstrap.DefaultBootstrapper;
import org.apache.tuscany.core.bootstrap.ExtensionActivator;
import org.apache.tuscany.core.builder.ConnectorImpl;
import org.apache.tuscany.core.component.ComponentManagerImpl;
import org.apache.tuscany.core.component.SimpleWorkContext;
import org.apache.tuscany.core.component.scope.CompositeScopeContainer;
import org.apache.tuscany.core.component.scope.ScopeRegistryImpl;
import org.apache.tuscany.core.deployer.DeployerImpl;
import org.apache.tuscany.core.monitor.NullMonitorFactory;
import org.apache.tuscany.core.resolver.AutowireResolver;
import org.apache.tuscany.core.resolver.DefaultAutowireResolver;
import org.apache.tuscany.core.services.classloading.ClassLoaderRegistryImpl;
import org.apache.tuscany.core.util.IOHelper;
import org.apache.tuscany.host.MonitorFactory;
import org.apache.tuscany.host.RuntimeInfo;
import org.apache.tuscany.host.management.ManagementService;
import org.apache.tuscany.host.monitor.FormatterRegistry;
import org.apache.tuscany.host.runtime.InitializationException;
import org.apache.tuscany.host.runtime.TuscanyRuntime;
import org.apache.tuscany.spi.builder.BuilderRegistry;
import org.apache.tuscany.spi.builder.Connector;
import org.apache.tuscany.spi.component.AtomicComponent;
import org.apache.tuscany.spi.component.Component;
import org.apache.tuscany.spi.component.ComponentManager;
import org.apache.tuscany.spi.component.RegistrationException;
import org.apache.tuscany.spi.component.ScopeContainerMonitor;
import org.apache.tuscany.spi.component.ScopeRegistry;
import org.apache.tuscany.spi.component.TargetResolutionException;
import org.apache.tuscany.spi.component.WorkContext;
import org.apache.tuscany.spi.deployer.Deployer;
import org.apache.tuscany.spi.idl.java.JavaServiceContract;
import org.apache.tuscany.spi.loader.LoaderRegistry;
import org.apache.tuscany.spi.services.classloading.ClassLoaderRegistry;
import org.apache.tuscany.spi.services.management.TuscanyManagementService;
import org.osoa.sca.ComponentContext;

/**
 * @version $Rev$ $Date$
 */
public abstract class AbstractRuntime<I extends RuntimeInfo> implements TuscanyRuntime<I> {
    private static final URI MONITOR_URI = TUSCANY_SYSTEM_ROOT.resolve("MonitorFactory");

    private static final URI COMPONENT_MGR_URI = TUSCANY_SYSTEM_ROOT.resolve("ComponentManager");

    private static final URI AUTOWIRE_RESOLVER_URI = TUSCANY_SYSTEM_ROOT.resolve("AutowireResolver");

    private static final URI SCOPE_REGISTRY_URI = TUSCANY_SYSTEM_ROOT.resolve("ScopeRegistry");

    private static final URI WORK_CONTEXT_URI = TUSCANY_SYSTEM.resolve("WorkContext");

    private static final URI RUNTIME_INFO_URI = TUSCANY_SYSTEM_ROOT.resolve("RuntimeInfo");

    private static final URI CLASSLOADER_REGISTRY_URI = TUSCANY_SYSTEM_ROOT.resolve("ClassLoaderRegistry");

    private static final URI HOST_CLASSLOADER_ID = URI.create("sca://./hostClassLoader");

    private static final URI BOOT_CLASSLOADER_ID = URI.create("sca://./bootClassLoader");

    protected final XMLInputFactory xmlFactory;
    protected URL systemScdl;
    protected String applicationName;
    protected URL applicationScdl;
    protected Class<I> runtimeInfoType;
    protected ManagementService<?> managementService;

    // primorial components automatically registered with the runtime
    /**
     * Information provided by the host about its runtime environment.
     */
    protected I runtimeInfo;

    /**
     * MonitorFactory provided by the host for directing events to its
     * management framework.
     */
    protected MonitorFactory monitorFactory;

    /**
     * The ComponentManager that manages all components in this runtime.
     */
    protected ComponentManager componentManager;

    /**
     * Registry for ClassLoaders used by this runtime.
     */
    protected ClassLoaderRegistry classLoaderRegistry;

    protected AutowireResolver resolver;

    protected Component systemComponent;
    protected Component tuscanySystem;

    protected ScopeRegistry scopeRegistry;
    protected Collection<ExtensionActivator> activators;

    protected AbstractRuntime(Class<I> runtimeInfoType) {
        this(runtimeInfoType, new NullMonitorFactory());
    }

    protected AbstractRuntime(Class<I> runtimeInfoType, MonitorFactory monitorFactory) {
        this.runtimeInfoType = runtimeInfoType;
        this.monitorFactory = monitorFactory;
        xmlFactory = XMLInputFactory.newInstance("javax.xml.stream.XMLInputFactory", getClass().getClassLoader());
        classLoaderRegistry = new ClassLoaderRegistryImpl();
        classLoaderRegistry.register(BOOT_CLASSLOADER_ID, getClass().getClassLoader());
    }

    public URL getSystemScdl() {
        return systemScdl;
    }

    public void setSystemScdl(URL systemScdl) {
        this.systemScdl = systemScdl;
    }

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public URL getApplicationScdl() {
        return applicationScdl;
    }

    public void setApplicationScdl(URL applicationScdl) {
        this.applicationScdl = applicationScdl;
    }

    public ClassLoader getHostClassLoader() {
        return classLoaderRegistry.getClassLoader(HOST_CLASSLOADER_ID);
    }

    public void setHostClassLoader(ClassLoader hostClassLoader) {
        classLoaderRegistry.register(HOST_CLASSLOADER_ID, hostClassLoader);
    }

    public I getRuntimeInfo() {
        return runtimeInfo;
    }

    public void setRuntimeInfo(I runtimeInfo) {
        this.runtimeInfo = runtimeInfo;
    }

    public MonitorFactory getMonitorFactory() {
        return monitorFactory;
    }

    public void setMonitorFactory(MonitorFactory monitorFactory) {
        this.monitorFactory = monitorFactory;
    }

    public ManagementService<?> getManagementService() {
        return managementService;
    }

    public void setManagementService(ManagementService<?> managementService) {
        this.managementService = managementService;
    }

    public void initialize() throws InitializationException {
        // URI name = TUSCANY_SYSTEM_ROOT.resolve("main");
        Bootstrapper bootstrapper = createBootstrapper();
        Deployer deployer = bootstrapper.createDeployer();
        registerSystemComponent(TUSCANY_DEPLOYER, Deployer.class, deployer);
        registerSystemComponent(WORK_CONTEXT_URI, WorkContext.class, new SimpleWorkContext());

        this.scopeRegistry = bootstrapper.getScopeRegistry();
        
        LoaderRegistry loaderRegistry = (LoaderRegistry)((DeployerImpl)deployer).getLoader();
        BuilderRegistry builderRegistry = (BuilderRegistry)((DeployerImpl)deployer).getBuilder();
        activators = getInstances(getHostClassLoader(), ExtensionActivator.class);
        for (ExtensionActivator activator : activators) {
            activator.start(loaderRegistry, builderRegistry);
        }

        registerBaselineSystemComponents();
    }

    public void destroy() {
        if (tuscanySystem != null) {
            tuscanySystem.stop();
            tuscanySystem = null;
        }
        if (systemComponent != null) {
            systemComponent.stop();
            systemComponent = null;
        }
    }

    public ComponentContext getComponentContext(URI componentId) {
        Component component = componentManager.getComponent(componentId);
        if (component == null) {
            return null;
        }
        return component.getComponentContext();
    }

    protected Bootstrapper createBootstrapper() {
        TuscanyManagementService tms = (TuscanyManagementService)getManagementService();
        resolver = new DefaultAutowireResolver();
        componentManager = new ComponentManagerImpl(tms, resolver);
        Connector connector = new ConnectorImpl(componentManager);
        return new DefaultBootstrapper(getMonitorFactory(), xmlFactory, componentManager, resolver, connector);
    }

    protected void registerBaselineSystemComponents() throws InitializationException {
        // register the RuntimeInfo provided by the host
        registerSystemComponent(RUNTIME_INFO_URI, runtimeInfoType, runtimeInfo);

        // register the MonitorFactory provided by the host
        List<Class<?>> monitorServices = new ArrayList<Class<?>>();
        monitorServices.add(MonitorFactory.class);
        monitorServices.add(FormatterRegistry.class);
        registerSystemComponent(MONITOR_URI, monitorServices, getMonitorFactory());

        // register the ClassLoaderRegistry
        registerSystemComponent(CLASSLOADER_REGISTRY_URI, ClassLoaderRegistry.class, classLoaderRegistry);

        // register the ComponentManager to that the fabric can wire to it
        registerSystemComponent(COMPONENT_MGR_URI, ComponentManager.class, componentManager);

        // register the AutowireResolver
        registerSystemComponent(AUTOWIRE_RESOLVER_URI, AutowireResolver.class, resolver);

        // register the ScopeRegistry
        registerSystemComponent(SCOPE_REGISTRY_URI, ScopeRegistry.class, scopeRegistry);
    }

    protected <S, I extends S> void registerSystemComponent(URI uri, Class<S> type, I component)
        throws InitializationException {
        try {
            JavaServiceContract<S> contract = new JavaServiceContract<S>(type);
            componentManager.registerJavaObject(uri, contract, component);
        } catch (RegistrationException e) {
            throw new InitializationException(e);
        }
    }

    protected <I> void registerSystemComponent(URI uri, List<Class<?>> types, I component)
        throws InitializationException {
        try {
            List<JavaServiceContract<?>> contracts = new ArrayList<JavaServiceContract<?>>();
            for (Class<?> type : types) {
                contracts.add(new JavaServiceContract(type));

            }
            componentManager.registerJavaObject(uri, contracts, component);
        } catch (RegistrationException e) {
            throw new InitializationException(e);
        }
    }

    protected ComponentManager getComponentManager() {
        return componentManager;
    }

    protected ScopeRegistry getScopeRegistry() {
        return scopeRegistry;
    }

    protected WorkContext getWorkContext() {
        try {
            AtomicComponent component = (AtomicComponent)getComponentManager().getComponent(WORK_CONTEXT_URI);
            return (WorkContext)component.getTargetInstance();
        } catch (TargetResolutionException e) {
            throw new AssertionError(e);
        }
    }

    protected Deployer getDeployer() {
        try {
            AtomicComponent component = (AtomicComponent)getComponentManager().getComponent(TUSCANY_DEPLOYER);
            return (Deployer)component.getTargetInstance();
        } catch (TargetResolutionException e) {
            throw new AssertionError(e);
        }
    }

    /**
     * Read the service name from a configuration file
     * 
     * @param classLoader
     * @param name The name of the service class
     * @return A class name which extends/implements the service class
     * @throws IOException
     */
    private static Set<String> getServiceNames(ClassLoader classLoader, String name) throws IOException {
        Set<String> set = new HashSet<String>();
        Enumeration<URL> urls = classLoader.getResources("META-INF/services/" + name);
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            String service = getServiceName(url);
            if (service != null) {
                set.add(service);

            }
        }
        return set;
    }

    private static String getServiceName(URL url) throws IOException {
        InputStream is = IOHelper.getInputStream(url);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is));
            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                } else if (!line.startsWith("#")) {
                    return line.trim();
                }
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return null;
    }

    private static <T> Collection<T> getInstances(final ClassLoader classLoader, Class<T> serviceClass) {
        List<T> instances = new ArrayList<T>();
        try {
            Set<String> services = getServiceNames(classLoader, serviceClass.getName());
            for (String className : services) {
                Class cls = Class.forName(className, true, classLoader);
                instances.add(serviceClass.cast(cls.newInstance())); // NOPMD
            }
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
        return instances;
    }
}