Remove deprecated API elements from protocol framework
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / impl / RpcProviderRegistryImpl.java
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 static com.google.common.base.Preconditions.checkState;
11
12 import java.util.EventListener;
13 import java.util.HashMap;
14 import java.util.Map;
15 import java.util.Map.Entry;
16 import java.util.Set;
17 import java.util.WeakHashMap;
18
19 import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
20 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
21 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangePublisher;
22 import org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils;
23 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
24 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
25 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
26 import org.opendaylight.controller.sal.binding.api.rpc.RpcContextIdentifier;
27 import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
28 import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeGenerator;
29 import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeHelper;
30 import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
31 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
32 import org.opendaylight.yangtools.concepts.ListenerRegistration;
33 import org.opendaylight.yangtools.concepts.util.ListenerRegistry;
34 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
35 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
36 import org.opendaylight.yangtools.yang.binding.RpcService;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public class RpcProviderRegistryImpl implements //
41         RpcProviderRegistry, //
42         RouteChangePublisher<RpcContextIdentifier, InstanceIdentifier<?>> {
43
44     private RuntimeCodeGenerator rpcFactory = SingletonHolder.RPC_GENERATOR_IMPL;
45
46     private final Map<Class<? extends RpcService>, RpcService> publicProxies = new WeakHashMap<>();
47     private final Map<Class<? extends RpcService>, RpcRouter<?>> rpcRouters = new WeakHashMap<>();
48     private final ListenerRegistry<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> routeChangeListeners = ListenerRegistry
49             .create();
50     private final ListenerRegistry<RouterInstantiationListener> routerInstantiationListener = ListenerRegistry.create();
51
52     private final static Logger LOG = LoggerFactory.getLogger(RpcProviderRegistryImpl.class);
53
54     private final String name;
55
56     private final ListenerRegistry<GlobalRpcRegistrationListener> globalRpcListeners = ListenerRegistry.create();
57
58     public String getName() {
59         return name;
60     }
61
62     public RpcProviderRegistryImpl(String name) {
63         super();
64         this.name = name;
65     }
66
67     @Override
68     public final <T extends RpcService> RoutedRpcRegistration<T> addRoutedRpcImplementation(Class<T> type,
69             T implementation) throws IllegalStateException {
70         return getRpcRouter(type).addRoutedRpcImplementation(implementation);
71     }
72
73     @Override
74     public final <T extends RpcService> RpcRegistration<T> addRpcImplementation(Class<T> type, T implementation)
75             throws IllegalStateException {
76         @SuppressWarnings("unchecked")
77         RpcRouter<T> potentialRouter = (RpcRouter<T>) rpcRouters.get(type);
78         if (potentialRouter != null) {
79             checkState(potentialRouter.getDefaultService() == null,
80                     "Default service for routed RPC already registered.");
81             return potentialRouter.registerDefaultService(implementation);
82         }
83         T publicProxy = getRpcService(type);
84         RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
85         checkState(currentDelegate == null, "Rpc service is already registered");
86         LOG.debug("Registering {} as global implementation of {} in {}", implementation, type.getSimpleName(), this);
87         RuntimeCodeHelper.setDelegate(publicProxy, implementation);
88         notifyGlobalRpcAdded(type);
89         return new RpcProxyRegistration<T>(type, implementation, this);
90     }
91
92     @SuppressWarnings("unchecked")
93     @Override
94     public final <T extends RpcService> T getRpcService(Class<T> type) {
95
96         @SuppressWarnings("unchecked")
97         T potentialProxy = (T) publicProxies.get(type);
98         if (potentialProxy != null) {
99             return potentialProxy;
100         }
101         synchronized (this) {
102             /**
103              * Potential proxy could be instantiated by other thread while we
104              * were waiting for the lock.
105              */
106
107             potentialProxy = (T) publicProxies.get(type);
108             if (potentialProxy != null) {
109                 return potentialProxy;
110             }
111             T proxy = rpcFactory.getDirectProxyFor(type);
112             LOG.debug("Created {} as public proxy for {} in {}", proxy, type.getSimpleName(), this);
113             publicProxies.put(type, proxy);
114             return proxy;
115         }
116     }
117
118     @SuppressWarnings("unchecked")
119     public <T extends RpcService> RpcRouter<T> getRpcRouter(Class<T> type) {
120         RpcRouter<?> potentialRouter = rpcRouters.get(type);
121         if (potentialRouter != null) {
122             return (RpcRouter<T>) potentialRouter;
123         }
124         synchronized (this) {
125             /**
126              * Potential Router could be instantiated by other thread while we
127              * were waiting for the lock.
128              */
129             potentialRouter = rpcRouters.get(type);
130             if (potentialRouter != null) {
131                 return (RpcRouter<T>) potentialRouter;
132             }
133             RpcRouter<T> router = rpcFactory.getRouterFor(type, name);
134             router.registerRouteChangeListener(new RouteChangeForwarder(type));
135             LOG.debug("Registering router {} as global implementation of {} in {}", router, type.getSimpleName(), this);
136             RuntimeCodeHelper.setDelegate(getRpcService(type), router.getInvocationProxy());
137             rpcRouters.put(type, router);
138             notifyListenersRoutedCreated(router);
139             return router;
140         }
141     }
142
143     private void notifyGlobalRpcAdded(Class<? extends RpcService> type) {
144         for(ListenerRegistration<GlobalRpcRegistrationListener> listener : globalRpcListeners) {
145             try {
146                 listener.getInstance().onGlobalRpcRegistered(type);
147             } catch (Exception e) {
148                 LOG.error("Unhandled exception during invoking listener {}", e);
149             }
150         }
151
152     }
153
154     private void notifyListenersRoutedCreated(RpcRouter router) {
155
156         for (ListenerRegistration<RouterInstantiationListener> listener : routerInstantiationListener) {
157             try {
158                 listener.getInstance().onRpcRouterCreated(router);
159             } catch (Exception e) {
160                 LOG.error("Unhandled exception during invoking listener {}", e);
161             }
162         }
163
164     }
165
166     public ListenerRegistration<RouterInstantiationListener> registerRouterInstantiationListener(
167             RouterInstantiationListener listener) {
168         ListenerRegistration<RouterInstantiationListener> reg = routerInstantiationListener.register(listener);
169         try {
170             for (RpcRouter<?> router : rpcRouters.values()) {
171                 listener.onRpcRouterCreated(router);
172             }
173         } catch (Exception e) {
174             LOG.error("Unhandled exception during invoking listener {}", e);
175         }
176         return reg;
177     }
178
179     @Override
180     public <L extends RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> ListenerRegistration<L> registerRouteChangeListener(
181             L listener) {
182         return (ListenerRegistration<L>) routeChangeListeners.register(listener);
183     }
184
185     public RuntimeCodeGenerator getRpcFactory() {
186         return rpcFactory;
187     }
188
189     public void setRpcFactory(RuntimeCodeGenerator rpcFactory) {
190         this.rpcFactory = rpcFactory;
191     }
192
193     public interface RouterInstantiationListener extends EventListener {
194         void onRpcRouterCreated(RpcRouter<?> router);
195     }
196
197     public ListenerRegistration<GlobalRpcRegistrationListener> registerGlobalRpcRegistrationListener(GlobalRpcRegistrationListener listener) {
198         return globalRpcListeners.register(listener);
199     }
200
201     public interface GlobalRpcRegistrationListener extends EventListener {
202         void onGlobalRpcRegistered(Class<? extends RpcService> cls);
203         void onGlobalRpcUnregistered(Class<? extends RpcService> cls);
204
205     }
206
207     private class RouteChangeForwarder<T extends RpcService> implements
208             RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
209
210         private final Class<T> type;
211
212         public RouteChangeForwarder(Class<T> type) {
213             this.type = type;
214         }
215
216         @Override
217         public void onRouteChange(RouteChange<Class<? extends BaseIdentity>, InstanceIdentifier<?>> change) {
218             Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> announcements = new HashMap<>();
219             for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getAnnouncements()
220                     .entrySet()) {
221                 RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
222                 announcements.put(key, entry.getValue());
223             }
224             Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> removals = new HashMap<>();
225             for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getRemovals()
226                     .entrySet()) {
227                 RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
228                 removals.put(key, entry.getValue());
229             }
230             RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> toPublish = RoutingUtils
231                     .<RpcContextIdentifier, InstanceIdentifier<?>> change(announcements, removals);
232             for (ListenerRegistration<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> listener : routeChangeListeners) {
233                 try {
234                     listener.getInstance().onRouteChange(toPublish);
235                 } catch (Exception e) {
236                     e.printStackTrace();
237                 }
238             }
239         }
240     }
241
242     public static class RpcProxyRegistration<T extends RpcService> extends AbstractObjectRegistration<T> implements
243             RpcRegistration<T> {
244
245         private final Class<T> serviceType;
246         private RpcProviderRegistryImpl registry;
247
248         public RpcProxyRegistration(Class<T> type, T service, RpcProviderRegistryImpl registry) {
249             super(service);
250             serviceType = type;
251         }
252
253         @Override
254         public Class<T> getServiceType() {
255             return serviceType;
256         }
257
258         @Override
259         protected void removeRegistration() {
260             if (registry != null) {
261                 T publicProxy = registry.getRpcService(serviceType);
262                 RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
263                 if (currentDelegate == getInstance()) {
264                     RuntimeCodeHelper.setDelegate(publicProxy, null);
265                 }
266                 registry = null;
267             }
268         }
269     }
270 }