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