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