bc53108675798173dd271b9bf18bf6db6fd3bb65
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / impl / OsgiConsumerContext.xtend
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.sal.binding.impl;
9
10 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ConsumerContext;
11 import org.opendaylight.controller.sal.binding.api.BindingAwareService;
12 import org.opendaylight.yangtools.yang.binding.RpcService;
13 import org.osgi.framework.BundleContext;
14 import org.osgi.framework.InvalidSyntaxException;
15 import org.osgi.framework.ServiceReference;
16 import org.slf4j.LoggerFactory
17 import static org.opendaylight.controller.sal.binding.impl.osgi.Constants.*
18
19 class OsgiConsumerContext implements ConsumerContext {
20
21     static val log = LoggerFactory.getLogger(OsgiConsumerContext)
22     protected val BundleContext bundleContext;
23     protected val BindingAwareBrokerImpl broker;
24
25     new(BundleContext ctx, BindingAwareBrokerImpl broker) {
26         this.bundleContext = ctx;
27         this.broker = broker;
28     }
29
30     override def <T extends BindingAwareService> getSALService(Class<T> service) {
31
32         // SAL Services are global
33         var ref = bundleContext.getServiceReference(service);
34         return bundleContext.getService(ref) as T;
35     }
36
37     override def <T extends RpcService> T getRpcService(Class<T> module) {
38         try {
39
40             val services = bundleContext.getServiceReferences(module, getProxyFilter());
41
42             // Proxy service found / using first implementation
43             // FIXME: Add advanced logic to retrieve service with right set of models
44             if (false == services.empty) {
45                 val ref = services.iterator().next() as ServiceReference<T>;
46                 return bundleContext.getService(ref) as T;
47             } else {
48                 broker.createDelegate(module);
49                 return getRpcService(module);
50             }
51         } catch (InvalidSyntaxException e) {
52             log.error("Created filter was invalid:", e.message, e)
53         }
54         return null;
55
56     }
57
58     private def getProxyFilter() {
59         return '''(«SAL_SERVICE_TYPE»=«SAL_SERVICE_TYPE_CONSUMER_PROXY»)'''
60     }
61 }