f0bf12cbc08c149011cab9c935153c52342d043a
[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 org.zeromq.ZMQ;
11
12 import java.net.Inet4Address;
13 import java.net.InetAddress;
14 import java.net.NetworkInterface;
15 import java.net.SocketException;
16 import java.util.Enumeration;
17
18 /**
19  * Provides a ZeroMQ Context object
20  */
21 public class Context {
22   private ZMQ.Context zmqContext = ZMQ.context(1);
23   private String uri;
24
25   private static Context _instance = new Context();
26
27   private Context() {}
28
29   public static Context getInstance(){
30     return _instance;
31   }
32
33   public ZMQ.Context getZmqContext(){
34     return this.zmqContext;
35   }
36
37   public String getLocalUri(){
38     uri = (uri != null) ? uri
39             : new StringBuilder("tcp://").append(getIpAddress()).append(":")
40               .append(getRpcPort()).toString();
41
42     return uri;
43   }
44
45   public String getRpcPort(){
46     String rpcPort = (System.getProperty("rpc.port") != null)
47         ? System.getProperty("rpc.port")
48         : "5554";
49
50     return rpcPort;
51   }
52
53   private String getIpAddress(){
54     String ipAddress = (System.getProperty("local.ip") != null)
55         ? System.getProperty("local.ip")
56         : findIpAddress();
57
58     return ipAddress;
59   }
60
61   /**
62    * Finds IPv4 address of the local VM
63    * TODO: This method is non-deterministic. There may be more than one IPv4 address. Cant say which
64    * address will be returned. Read IP from a property file or enhance the code to make it deterministic.
65    * Should we use IP or hostname?
66    *
67    * @return
68    */
69   private String findIpAddress() {
70     String hostAddress = null;
71     Enumeration e = null;
72     try {
73       e = NetworkInterface.getNetworkInterfaces();
74     } catch (SocketException e1) {
75       e1.printStackTrace();
76     }
77     while (e.hasMoreElements()) {
78
79       NetworkInterface n = (NetworkInterface) e.nextElement();
80
81       Enumeration ee = n.getInetAddresses();
82       while (ee.hasMoreElements()) {
83         InetAddress i = (InetAddress) ee.nextElement();
84         if ((i instanceof Inet4Address) && (i.isSiteLocalAddress()))
85           hostAddress = i.getHostAddress();
86       }
87     }
88     return hostAddress;
89
90   }
91 }