summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/modules/node-impl-osgi/src/main/java/org/apache/tuscany/sca/osgi/remoteserviceadmin/impl/RemoteServiceAdminImpl.java
blob: 94955ada3873568fc347077b3f92f9fab239023a (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
/*
 * 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.sca.osgi.remoteserviceadmin.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.apache.tuscany.sca.core.ExtensionPointRegistry;
import org.apache.tuscany.sca.core.UtilityExtensionPoint;
import org.apache.tuscany.sca.definitions.Definitions;
import org.apache.tuscany.sca.deployment.Deployer;
import org.apache.tuscany.sca.policy.BindingType;
import org.apache.tuscany.sca.policy.Intent;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.ExportReference;
import org.osgi.service.remoteserviceadmin.ExportRegistration;
import org.osgi.service.remoteserviceadmin.ImportReference;
import org.osgi.service.remoteserviceadmin.ImportRegistration;
import org.osgi.service.remoteserviceadmin.RemoteConstants;
import org.osgi.service.remoteserviceadmin.RemoteServiceAdmin;
import org.osgi.service.remoteserviceadmin.RemoteServiceAdminEvent;
import org.osgi.service.remoteserviceadmin.RemoteServiceAdminListener;
import org.osgi.util.tracker.ServiceTracker;

/**
 * SCA Implementation of {@link RemoteServiceAdmin}
 */
public class RemoteServiceAdminImpl implements RemoteServiceAdmin, ManagedService {
    private BundleContext context;
    private ServiceRegistration registration;
    private ServiceRegistration managedService;
    private ServiceTracker listeners;

    private OSGiServiceExporter exporter;
    private OSGiServiceImporter importer;

    private Collection<ImportRegistration> importRegistrations = new ArrayList<ImportRegistration>();
    private Collection<ExportRegistration> exportedRegistrations = new ArrayList<ExportRegistration>();

    public RemoteServiceAdminImpl(BundleContext context) {
        this.context = context;
    }

    public void start() {
        this.exporter = new OSGiServiceExporter(context);
        this.importer = new OSGiServiceImporter(context);
        exporter.start();
        importer.start();
        Hashtable<String, Object> props = new Hashtable<String, Object>();
        props.put(RemoteConstants.REMOTE_CONFIGS_SUPPORTED, new String[] {"org.osgi.sca"});
        
        ExtensionPointRegistry registry = exporter.getExtensionPointRegistry();
        UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class);
        Deployer deployer = utilities.getUtility(Deployer.class);
        Definitions definitions = deployer.getSystemDefinitions();

        String[] intents = new String[definitions.getIntents().size()];
        int i = 0;
        for (Intent intent : definitions.getIntents()) {
            intents[i++] = intent.toString();
        }

        String[] bindingTypes = new String[definitions.getBindingTypes().size()];
        i = 0;
        for (BindingType bindingType : definitions.getBindingTypes()) {
            bindingTypes[i++] = bindingType.getType().toString();
        }
        
        // FIXME: We should ask SCA domain for the supported intents
        props.put(RemoteConstants.REMOTE_INTENTS_SUPPORTED, intents);
        // FIXME: We should ask SCA domain for the supported binding types
        props.put("org.osgi.sca.binding.types", bindingTypes);
        registration = context.registerService(RemoteServiceAdmin.class.getName(), this, props);
        
        props = new Hashtable<String, Object>();
        props.put(Constants.SERVICE_PID, RemoteServiceAdminImpl.class.getName());
        managedService = context.registerService(ManagedService.class.getName(), this, props);
        listeners = new ServiceTracker(this.context, RemoteServiceAdminListener.class.getName(), null);
        listeners.open();
    }

    public void stop() {
        if (registration != null) {
            try {
                registration.unregister();
            } catch (IllegalStateException e) {
                // The service has been unregistered, ignore it
            }
            registration = null;
        }
        if (managedService != null) {
            try {
                managedService.unregister();
            } catch (IllegalStateException e) {
                // The service has been unregistered, ignore it
            }
            managedService = null;
        }
        if (listeners != null) {
            listeners.close();
            listeners = null;
        }
        for (ExportRegistration exportRegistration : exportedRegistrations) {
            exportRegistration.close();
        }
        exportedRegistrations.clear();
        for (ImportRegistration importRegistration : importRegistrations) {
            importRegistration.close();
        }
        importRegistrations.clear();
        if (importer != null) {
            importer.stop();
            importer = null;
        }
        if (exporter != null) {
            exporter.stop();
            exporter = null;
        }
    }

    /**
     * @see org.osgi.remoteserviceadmin.RemoteServiceAdmin#exportService(org.osgi.framework.ServiceReference,
     *      java.util.Map)
     */
    public List<ExportRegistration> exportService(ServiceReference ref, Map properties) {
        List<ExportRegistration> exportRegistrations = exporter.exportService(ref, properties);
        if (exportRegistrations != null) {
            exportRegistrations.addAll(exportedRegistrations);
            fireExportEvents(ref.getBundle(), exportRegistrations);
        }
        return exportRegistrations;
    }

    private void fireExportEvents(Bundle source, List<ExportRegistration> exportRegistrations) {
        for (ExportRegistration registration : exportRegistrations) {
            RemoteServiceAdminEvent rsaEvent =
                new RemoteServiceAdminEvent(RemoteServiceAdminEvent.EXPORT_REGISTRATION, source, registration
                    .getExportReference(), registration.getException());
            EventAdmin eventAdmin = getEventAdmin();
            if (eventAdmin != null) {
                eventAdmin.postEvent(wrap(rsaEvent));
            }
            for (Object listener : listeners.getServices()) {
                RemoteServiceAdminListener rsaListener = (RemoteServiceAdminListener)listener;
                rsaListener.remoteAdminEvent(rsaEvent);
            }
        }
    }

    private EventAdmin getEventAdmin() {
        ServiceReference reference = context.getServiceReference(EventAdmin.class.getName());
        if (reference == null) {
            return null;
        } else {
            return (EventAdmin)context.getService(reference);
        }
    }

    private Event wrap(RemoteServiceAdminEvent rsaEvent) {
        int type = rsaEvent.getType();
        String eventType = null;
        switch (type) {
            case RemoteServiceAdminEvent.EXPORT_ERROR:
                eventType = "EXPORT_ERROR";
                break;
            case RemoteServiceAdminEvent.EXPORT_REGISTRATION:
                eventType = "EXPORT_REGISTRATION";
                break;
            case RemoteServiceAdminEvent.EXPORT_UNREGISTRATION:
                eventType = "EXPORT_UNREGISTRATION";
                break;
            case RemoteServiceAdminEvent.EXPORT_WARNING:
                eventType = "EXPORT_WARNING";
                break;
            case RemoteServiceAdminEvent.IMPORT_ERROR:
                eventType = "IMPORT_ERROR";
                break;
            case RemoteServiceAdminEvent.IMPORT_REGISTRATION:
                eventType = "IMPORT_REGISTRATION";
                break;
            case RemoteServiceAdminEvent.IMPORT_UNREGISTRATION:
                eventType = "EXPORT_ERROR";
                break;
            case RemoteServiceAdminEvent.IMPORT_WARNING:
                eventType = "IMPORT_UNREGISTRATION";
                break;
        }
        String topic = "org/osgi/service/remoteserviceadmin/" + eventType;
        Map<String, Object> props = new HashMap<String, Object>();
         /*
          * <ul>
         <li>bundle  (Bundle) The Remote Service Admin bundle
         <li>bundle-id  (Long) The id of the Blueprint bundle.
         <li>bundle-symbolicname  (String) The Bundle Symbolic Name of the
         Remote Service Admin bundle.
         <li>bundle-version - (Version) The version of the Blueprint bundle.
         <li>cause  The exception, if present.
         <li>import.registration  An imported endpoint, if present
         <li>export.registration  An exported endpoint, if present
         <li>service.remote.id  Remote service UUID, if present
         <li>service.remote.uuid  Remote service UUID, if present
         <li>service.remote.uri  (String) The URI of the endpoint, if present
         <li>objectClass  (String[]) The interface names, if present
         <li>service.imported.configs  (String+) The configuration types of the
         imported services, if present
         <li>timestamp  (Long) The time when the event occurred
         <li>event  (RemoteServiceAdminEvent) The RemoteServiceAdminEvent
         object that caused this event.
         </ul>
        */
        Bundle rsaBundle = context.getBundle();
        props.put("bundle", rsaBundle);
        props.put("bundle-id", rsaBundle.getBundleId());
        props.put("bundle-symbolicname", rsaBundle.getSymbolicName());
        props.put("bundle-version", rsaBundle.getHeaders().get(Constants.BUNDLE_VERSION));
        props.put("cause", rsaEvent.getException());
        props.put("import.registration", rsaEvent.getImportReference());
        props.put("export.registration", rsaEvent.getExportReference());
        EndpointDescription ep = null;
        if (rsaEvent.getImportReference() != null) {
            ep = rsaEvent.getImportReference().getImportedEndpoint();
        } 
        if (rsaEvent.getExportReference() != null) {
            ep = rsaEvent.getExportReference().getExportedEndpoint();
        }
        
        if (ep != null) {
            props.put("endpoint.service.id", ep.getServiceId());
            props.put("endpoint.framework.uuid", ep.getFrameworkUUID());
            props.put("endpoint.id", ep.getId());
            props.put("objectClass", ep.getInterfaces());
            props.put("service.imported.configs", ep.getConfigurationTypes());
            Object bindings = ep.getProperties().get("org.osgi.sca.bindings");
            if (bindings != null) {
                props.put("org.osgi.sca.bindings", bindings);
            }
            Object config = ep.getProperties().get("org.osgi.sca.config.url");
            if (config != null) {
                props.put("org.osgi.sca.config.url", config);
            }
            config = ep.getProperties().get("org.osgi.sca.config.xml");
            if (config != null) {
                props.put("org.osgi.sca.config.xml", config);
            }        }
        props.put("timestamp", Long.valueOf(System.currentTimeMillis()));
        props.put("event", rsaEvent);
        return new Event(topic, props);
    }

    private void fireImportEvents(Bundle source, ImportRegistration registration) {
        RemoteServiceAdminEvent rsaEvent =
            new RemoteServiceAdminEvent(RemoteServiceAdminEvent.IMPORT_REGISTRATION, source, registration
                .getImportReference(), registration.getException());
        EventAdmin eventAdmin = getEventAdmin();
        if (eventAdmin != null) {
            eventAdmin.postEvent(wrap(rsaEvent));
        }
        for (Object listener : listeners.getServices()) {
            RemoteServiceAdminListener rsaListener = (RemoteServiceAdminListener)listener;
            rsaListener.remoteAdminEvent(rsaEvent);
        }
    }

    /**
     * @see org.osgi.remoteserviceadmin.RemoteServiceAdmin#getExportedServices()
     */
    public Collection<ExportReference> getExportedServices() {
        Collection<ExportReference> exportedServices = new ArrayList<ExportReference>();
        for (ExportRegistration registration : exportedRegistrations) {
            exportedServices.add(registration.getExportReference());
        }
        return exportedServices;
    }

    /**
     * @see org.osgi.remoteserviceadmin.RemoteServiceAdmin#getImportedEndpoints()
     */
    public Collection<ImportReference> getImportedEndpoints() {
        Collection<ImportReference> importedEndpoints = new ArrayList<ImportReference>();
        for (ImportRegistration registration : importRegistrations) {
            importedEndpoints.add(registration.getImportReference());
        }
        return importedEndpoints;
    }

    /**
     * @see org.osgi.remoteserviceadmin.RemoteServiceAdmin#importService(org.apache.tuscany.sca.dosgi.discovery.EndpointDescription)
     */
    public ImportRegistration importService(EndpointDescription endpoint) {
        Bundle bundle = (Bundle)endpoint.getProperties().get(Bundle.class.getName());
        ImportRegistration importReg = importer.importService(bundle, endpoint);
        if (importReg != null) {
            fireImportEvents(bundle, importReg);
            importRegistrations.add(importReg);
        }
        return importReg;
    }

    public synchronized void updated(Dictionary props) throws ConfigurationException {
        if (props == null) {
            // It can be null in Apache Felix
            return;
        }
        String domainRegistry = (String)props.get("org.osgi.sca.domain.registry");
        String domainURI = (String)props.get("org.osgi.sca.domain.uri");
        if (domainRegistry != null) {
            exporter.setDomainRegistry(domainRegistry);
            importer.setDomainRegistry(domainRegistry);
        }
        if (domainURI != null) {
            exporter.setDomainURI(domainURI);
            importer.setDomainURI(domainURI);
        }
    }
}