Bug 8055: use lambdas instead of anonymous classes
[ovsdb.git] / library / impl / src / main / java / org / opendaylight / ovsdb / lib / jsonrpc / JsonRpcEndpoint.java
1 /*
2  * Copyright © 2013, 2017 EBay Software Foundation 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
9 package org.opendaylight.ovsdb.lib.jsonrpc;
10
11 import com.fasterxml.jackson.core.JsonProcessingException;
12 import com.fasterxml.jackson.databind.JavaType;
13 import com.fasterxml.jackson.databind.JsonNode;
14 import com.fasterxml.jackson.databind.ObjectMapper;
15 import com.fasterxml.jackson.databind.type.TypeFactory;
16 import com.google.common.collect.Maps;
17 import com.google.common.reflect.Invokable;
18 import com.google.common.reflect.Reflection;
19 import com.google.common.reflect.TypeToken;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.SettableFuture;
22 import com.google.common.util.concurrent.ThreadFactoryBuilder;
23 import io.netty.channel.Channel;
24
25 import java.lang.reflect.InvocationTargetException;
26 import java.lang.reflect.Method;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.UUID;
30 import java.util.concurrent.Executors;
31 import java.util.concurrent.ScheduledExecutorService;
32 import java.util.concurrent.ThreadFactory;
33 import java.util.concurrent.TimeUnit;
34
35 import org.opendaylight.ovsdb.lib.error.UnexpectedResultException;
36 import org.opendaylight.ovsdb.lib.error.UnsupportedArgumentException;
37 import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public class JsonRpcEndpoint {
42
43     private static final Logger LOG = LoggerFactory.getLogger(JsonRpcEndpoint.class);
44     private static final int REAPER_THREADS = 3;
45     private static final ThreadFactory FUTURE_REAPER_THREAD_FACTORY = new ThreadFactoryBuilder()
46             .setNameFormat("OVSDB-Lib-Future-Reaper-%d")
47             .setDaemon(true).build();
48     private static final ScheduledExecutorService FUTURE_REAPER_SERVICE
49             = Executors.newScheduledThreadPool(REAPER_THREADS, FUTURE_REAPER_THREAD_FACTORY);
50
51     private static int reaperInterval = 1000;
52
53     public class CallContext {
54         Method method;
55         JsonRpc10Request request;
56         SettableFuture<Object> future;
57
58         public CallContext(JsonRpc10Request request, Method method, SettableFuture<Object> future) {
59             this.method = method;
60             this.request = request;
61             this.future = future;
62         }
63
64         public Method getMethod() {
65             return method;
66         }
67
68         public JsonRpc10Request getRequest() {
69             return request;
70         }
71
72         public SettableFuture<Object> getFuture() {
73             return future;
74         }
75     }
76
77     ObjectMapper objectMapper;
78     Channel nettyChannel;
79     Map<String, CallContext> methodContext = Maps.newHashMap();
80     Map<Object, OvsdbRPC.Callback> requestCallbacks = Maps.newHashMap();
81
82     public JsonRpcEndpoint(ObjectMapper objectMapper, Channel channel) {
83         this.objectMapper = objectMapper;
84         this.nettyChannel = channel;
85     }
86
87     public <T> T getClient(final Object context, Class<T> klazz) {
88
89         return Reflection.newProxy(klazz, (proxy, method, args) -> {
90             if (method.getName().equals(OvsdbRPC.REGISTER_CALLBACK_METHOD)) {
91                 if ((args == null) || args.length != 1 || !(args[0] instanceof OvsdbRPC.Callback)) {
92                     return false;
93                 }
94                 requestCallbacks.put(context, (OvsdbRPC.Callback)args[0]);
95                 return true;
96             }
97
98             JsonRpc10Request request = new JsonRpc10Request(UUID.randomUUID().toString());
99             request.setMethod(method.getName());
100
101             if (args != null && args.length != 0) {
102                 List<Object> params = null;
103
104                 if (args.length == 1) {
105                     if (args[0] instanceof Params) {
106                         params = ((Params) args[0]).params();
107                     } else if (args[0] instanceof List) {
108                         params = (List<Object>) args[0];
109                     }
110
111                     if (params == null) {
112                         throw new UnsupportedArgumentException("do not understand this argument yet");
113                     }
114                     request.setParams(params);
115                 }
116             }
117
118             String requestString = objectMapper.writeValueAsString(request);
119             LOG.trace("getClient Request : {}", requestString);
120
121             SettableFuture<Object> sf = SettableFuture.create();
122             methodContext.put(request.getId(), new CallContext(request, method, sf));
123             FUTURE_REAPER_SERVICE.schedule(() -> {
124                 CallContext cc = methodContext.remove(request.getId());
125                 if (cc != null) {
126                     if (cc.getFuture().isDone() || cc.getFuture().isCancelled()) {
127                         return;
128                     }
129                     cc.getFuture().cancel(false);
130                 }
131             }, reaperInterval, TimeUnit.MILLISECONDS);
132
133             nettyChannel.writeAndFlush(requestString);
134
135             return sf;
136         }
137         );
138     }
139
140     public void processResult(JsonNode response) throws NoSuchMethodException {
141
142         LOG.trace("Response : {}", response.toString());
143         CallContext returnCtxt = methodContext.remove(response.get("id").asText());
144         if (returnCtxt == null) {
145             return;
146         }
147
148         if (ListenableFuture.class == returnCtxt.getMethod().getReturnType()) {
149             TypeToken<?> retType = TypeToken.of(
150                     returnCtxt.getMethod().getGenericReturnType())
151                     .resolveType(ListenableFuture.class.getMethod("get").getGenericReturnType());
152             JavaType javaType =  TypeFactory.defaultInstance().constructType(retType.getType());
153
154             JsonNode result = response.get("result");
155             Object result1 = objectMapper.convertValue(result, javaType);
156             JsonNode error = response.get("error");
157             if (error != null && !error.isNull()) {
158                 LOG.error("Error : {}", error.toString());
159             }
160
161             returnCtxt.getFuture().set(result1);
162
163         } else {
164             throw new UnexpectedResultException("Don't know how to handle this");
165         }
166     }
167
168     public void processRequest(Object context, JsonNode requestJson) {
169         JsonRpc10Request request = new JsonRpc10Request(requestJson.get("id").asText());
170         request.setMethod(requestJson.get("method").asText());
171         LOG.trace("Request : {} {} {}", requestJson.get("id"), requestJson.get("method"),
172                 requestJson.get("params"));
173         OvsdbRPC.Callback callback = requestCallbacks.get(context);
174         if (callback != null) {
175             Method[] methods = callback.getClass().getDeclaredMethods();
176             for (Method method : methods) {
177                 if (method.getName().equals(request.getMethod())) {
178                     Class<?>[] parameters = method.getParameterTypes();
179                     JsonNode params = requestJson.get("params");
180                     Object param = objectMapper.convertValue(params, parameters[1]);
181                     try {
182                         Invokable from = Invokable.from(method);
183                         from.setAccessible(true);
184                         from.invoke(callback, context, param);
185                     } catch (IllegalAccessException | InvocationTargetException e) {
186                         LOG.error("Unable to invoke callback {}", method.getName(), e);
187                     }
188                     return;
189                 }
190             }
191         }
192
193         // Echo dont need any special processing. hence handling it internally.
194
195         if (request.getMethod().equals("echo")) {
196             JsonRpc10Response response = new JsonRpc10Response(request.getId());
197             response.setError(null);
198             String jsonString = null;
199             try {
200                 jsonString = objectMapper.writeValueAsString(response);
201                 nettyChannel.writeAndFlush(jsonString);
202             } catch (JsonProcessingException e) {
203                 LOG.error("Exception while processing JSON string {}", jsonString, e);
204             }
205             return;
206         }
207
208         // send a null response for list_dbs
209         if (request.getMethod().equals("list_dbs")) {
210             JsonRpc10Response response = new JsonRpc10Response(request.getId());
211             response.setError(null);
212             String jsonString = null;
213             try {
214                 jsonString = objectMapper.writeValueAsString(response);
215                 nettyChannel.writeAndFlush(jsonString);
216             } catch (JsonProcessingException e) {
217                 LOG.error("Exception while processing JSON string {}", jsonString, e);
218             }
219             return;
220         }
221
222         LOG.error("No handler for Request : {} on {}", requestJson.toString(), context);
223     }
224
225     public Map<String, CallContext> getMethodContext() {
226         return methodContext;
227     }
228
229     public static void setReaperInterval(int interval) {
230         reaperInterval = interval;
231         LOG.info("Ovsdb Rpc Task interval is set to {} millisecond", reaperInterval);
232     }
233
234     public static void close() {
235         LOG.info("Shutting down reaper executor service");
236         FUTURE_REAPER_SERVICE.shutdownNow();
237     }
238 }