b58931442ef51d46ad954c21b9ca9bac20fc418a
[ovsdb.git] / library / impl / src / main / java / org / opendaylight / ovsdb / lib / jsonrpc / JsonRpcServiceBinderHandler.java
1 /*
2  * Copyright (c) 2013, 2015 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.databind.JsonNode;
12 import com.google.common.base.Strings;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.channel.ChannelInboundHandlerAdapter;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17
18 public class JsonRpcServiceBinderHandler extends ChannelInboundHandlerAdapter {
19     private static final Logger LOG = LoggerFactory.getLogger(JsonRpcServiceBinderHandler.class);
20     JsonRpcEndpoint factory = null;
21     Object context = null;
22
23     public Object getContext() {
24         return context;
25     }
26
27     public void setContext(Object context) {
28         this.context = context;
29     }
30
31     public JsonRpcServiceBinderHandler(JsonRpcEndpoint factory) {
32         this.factory = factory;
33     }
34
35     @Override
36     public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
37         if (msg instanceof JsonNode) {
38             JsonNode jsonNode = (JsonNode) msg;
39             if (jsonNode.has("result")) {
40                 try {
41                     factory.processResult(jsonNode);
42                 } catch (NoSuchMethodException e) {
43                      /*
44                        ChannelRead is a method invoked during Netty message receive event.
45                        The only sane thing we can do is to print a meaningful error message.
46                      */
47                     LOG.error("NoSuchMethodException when handling {}", msg, e);
48                 }
49             } else if (jsonNode.hasNonNull("method")) {
50                 if (jsonNode.has("id") && !Strings.isNullOrEmpty(jsonNode.get("id").asText())) {
51                     factory.processRequest(context, jsonNode);
52                 } else {
53                     LOG.debug("Request with null or empty id field: {} {}", jsonNode.get("method"),
54                             jsonNode.get("params"));
55                 }
56             }
57
58             return;
59         }
60         ctx.channel().close();
61     }
62
63     @Override
64     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
65         ctx.flush();
66     }
67 }