Merge "BUG-731: fix warnings from missing generic arguments"
[controller.git] / opendaylight / md-sal / sal-remoterpc-connector / implementation / src / main / java / org / opendaylight / controller / sal / connector / remoterpc / Context.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  * This program and the accompanying materials are made available under the
4  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
5  * and is available at http://www.eclipse.org/legal/epl-v10.html
6  */
7
8 package org.opendaylight.controller.sal.connector.remoterpc;
9
10 import java.net.Inet4Address;
11 import java.net.InetAddress;
12 import java.net.NetworkInterface;
13 import java.net.SocketException;
14 import java.util.Enumeration;
15
16 import org.zeromq.ZMQ;
17
18 /**
19  * Provides a ZeroMQ Context object
20  */
21 public class Context {
22   private final ZMQ.Context zmqContext = ZMQ.context(1);
23   private String uri;
24   private final String DEFAULT_RPC_PORT = "5554";
25
26   private static Context _instance = new Context();
27
28   private Context() {}
29
30   public static Context getInstance(){
31     return _instance;
32   }
33
34   public ZMQ.Context getZmqContext(){
35     return this.zmqContext;
36   }
37
38   public String getLocalUri(){
39     uri = (uri != null) ? uri
40             : new StringBuilder().append(getIpAddress()).append(":")
41               .append(getRpcPort()).toString();
42
43     return uri;
44   }
45
46   public String getRpcPort(){
47     String rpcPort = (System.getProperty("rpc.port") != null)
48         ? System.getProperty("rpc.port")
49         : DEFAULT_RPC_PORT;
50
51     return rpcPort;
52   }
53
54   private String getIpAddress(){
55     String ipAddress = (System.getProperty("local.ip") != null)
56         ? System.getProperty("local.ip")
57         : findIpAddress();
58
59     return ipAddress;
60   }
61
62   /**
63    * Finds IPv4 address of the local VM
64    * TODO: This method is non-deterministic. There may be more than one IPv4 address. Cant say which
65    * address will be returned. Read IP from a property file or enhance the code to make it deterministic.
66    * Should we use IP or hostname?
67    *
68    * @return
69    */
70   private String findIpAddress() {
71     String hostAddress = null;
72     Enumeration<?> e = null;
73     try {
74       e = NetworkInterface.getNetworkInterfaces();
75     } catch (SocketException e1) {
76       e1.printStackTrace();
77     }
78     while (e.hasMoreElements()) {
79
80       NetworkInterface n = (NetworkInterface) e.nextElement();
81
82       Enumeration<?> ee = n.getInetAddresses();
83       while (ee.hasMoreElements()) {
84         InetAddress i = (InetAddress) ee.nextElement();
85         if ((i instanceof Inet4Address) && (i.isSiteLocalAddress()))
86           hostAddress = i.getHostAddress();
87       }
88     }
89     return hostAddress;
90
91   }
92 }