2 * Copyright (C) 2013 EBay Software Foundation
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
8 * Authors : Ashwin Raveendran, Madhu Venugopal
10 package org.opendaylight.ovsdb.lib.jsonrpc;
12 import io.netty.channel.Channel;
14 import java.lang.reflect.InvocationHandler;
15 import java.lang.reflect.InvocationTargetException;
16 import java.lang.reflect.Method;
17 import java.util.List;
19 import java.util.UUID;
21 import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
25 import com.fasterxml.jackson.core.JsonProcessingException;
26 import com.fasterxml.jackson.databind.JavaType;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import com.fasterxml.jackson.databind.type.TypeFactory;
30 import com.google.common.collect.Maps;
31 import com.google.common.reflect.Reflection;
32 import com.google.common.reflect.TypeToken;
33 import com.google.common.util.concurrent.ListenableFuture;
34 import com.google.common.util.concurrent.SettableFuture;
36 public class JsonRpcEndpoint {
38 protected static final Logger logger = LoggerFactory.getLogger(JsonRpcEndpoint.class);
40 public class CallContext {
42 JsonRpc10Request request;
43 SettableFuture<Object> future;
45 public CallContext(JsonRpc10Request request, Method method, SettableFuture<Object> future) {
47 this.request = request;
51 public Method getMethod() {
55 public JsonRpc10Request getRequest() {
59 public SettableFuture<Object> getFuture() {
64 ObjectMapper objectMapper;
66 Map<String, CallContext> methodContext = Maps.newHashMap();
67 Map<Object, OvsdbRPC.Callback> requestCallbacks = Maps.newHashMap();
69 public JsonRpcEndpoint(ObjectMapper objectMapper, Channel channel) {
70 this.objectMapper = objectMapper;
71 this.nettyChannel = channel;
74 public <T> T getClient(final Object context, Class<T> klazz) {
76 return Reflection.newProxy(klazz, new InvocationHandler() {
78 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
79 if (method.getName().equals(OvsdbRPC.REGISTER_CALLBACK_METHOD)) {
80 if ((args == null) || args.length != 1 || !(args[0] instanceof OvsdbRPC.Callback)) return false;
81 requestCallbacks.put(context, (OvsdbRPC.Callback)args[0]);
85 JsonRpc10Request request = new JsonRpc10Request(UUID.randomUUID().toString());
86 request.setMethod(method.getName());
88 if (args != null && args.length != 0) {
89 List<Object> params = null;
91 if (args.length == 1) {
92 if (args[0] instanceof Params) {
93 params = ((Params) args[0]).params();
94 } else if (args[0] instanceof List) {
95 params = (List<Object>) args[0];
99 throw new RuntimeException("do not understand this argument yet");
101 request.setParams(params);
105 String s = objectMapper.writeValueAsString(request);
106 logger.trace("{}", s);
108 SettableFuture<Object> sf = SettableFuture.create();
109 methodContext.put(request.getId(), new CallContext(request, method, sf));
111 nettyChannel.writeAndFlush(s);
119 public void processResult(JsonNode response) throws NoSuchMethodException {
121 logger.trace("Response : {}", response.toString());
122 CallContext returnCtxt = methodContext.get(response.get("id").asText());
123 if (returnCtxt == null) return;
125 if (ListenableFuture.class == returnCtxt.getMethod().getReturnType()) {
126 TypeToken<?> retType = TypeToken.of(
127 returnCtxt.getMethod().getGenericReturnType())
128 .resolveType(ListenableFuture.class.getMethod("get").getGenericReturnType());
129 JavaType javaType = TypeFactory.defaultInstance().constructType (retType.getType());
131 JsonNode result = response.get("result");
132 logger.trace("Result : {}", result.toString());
134 Object result1 = objectMapper.convertValue(result, javaType);
135 JsonNode error = response.get("error");
136 if (error != null && !error.isNull()) {
137 logger.error("Error : {}", error.toString());
140 returnCtxt.getFuture().set(result1);
143 throw new RuntimeException("donno how to deal with this");
147 public void processRequest(Object context, JsonNode requestJson) {
148 JsonRpc10Request request = new JsonRpc10Request(requestJson.get("id").asText());
149 request.setMethod(requestJson.get("method").asText());
150 logger.trace("Request : {} {}", requestJson.get("method"), requestJson.get("params"));
151 OvsdbRPC.Callback callback = requestCallbacks.get(context);
152 if (callback != null) {
153 Method[] methods = callback.getClass().getDeclaredMethods();
154 for (Method m : methods) {
155 if (m.getName().equals(request.getMethod())) {
156 Class<?>[] parameters = m.getParameterTypes();
157 JsonNode params = requestJson.get("params");
158 Object param = objectMapper.convertValue(params, parameters[1]);
160 m.invoke(callback, context, param);
161 } catch (IllegalAccessException | InvocationTargetException e) {
162 logger.error("Unable to invoke callback " + m.getName(), e);
169 // Echo dont need any special processing. hence handling it internally.
171 if (request.getMethod().equals("echo")) {
172 JsonRpc10Response response = new JsonRpc10Response(request.getId());
173 response.setError(null);
176 s = objectMapper.writeValueAsString(response);
177 nettyChannel.writeAndFlush(s);
178 } catch (JsonProcessingException e) {
179 logger.error("Exception while processing JSON string " + s, e );
184 logger.error("No handler for Request : {} on {}",requestJson.toString(), context);
187 public Map<String, CallContext> getMethodContext() {
188 return methodContext;