Refactor Prov DB handling
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / beans / NodeClass.java
1 /*******************************************************************************\r
2  * ============LICENSE_START==================================================\r
3  * * org.onap.dmaap\r
4  * * ===========================================================================\r
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * * ===========================================================================\r
7  * * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * * you may not use this file except in compliance with the License.\r
9  * * You may obtain a copy of the License at\r
10  * *\r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * *\r
13  *  * Unless required by applicable law or agreed to in writing, software\r
14  * * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * * See the License for the specific language governing permissions and\r
17  * * limitations under the License.\r
18  * * ============LICENSE_END====================================================\r
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 \r
24 package org.onap.dmaap.datarouter.provisioning.beans;\r
25 \r
26 import com.att.eelf.configuration.EELFLogger;\r
27 import com.att.eelf.configuration.EELFManager;\r
28 import java.sql.Connection;\r
29 import java.sql.PreparedStatement;\r
30 import java.sql.ResultSet;\r
31 import java.sql.SQLException;\r
32 import java.util.Collection;\r
33 import java.util.HashMap;\r
34 import java.util.Map;\r
35 import java.util.Set;\r
36 import java.util.TreeSet;\r
37 import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;\r
38 \r
39 /**\r
40  * This class is used to aid in the mapping of node names from/to node IDs.\r
41  *\r
42  * @author Robert P. Eby\r
43  * @version $Id: NodeClass.java,v 1.2 2014/01/15 16:08:43 eby Exp $\r
44  */\r
45 \r
46 public abstract class NodeClass extends Syncable {\r
47 \r
48     private static final String PROV_0005_DO_INSERT = "PROV0005 doInsert: ";\r
49     private static Map<String, Integer> nodesMap;\r
50     private static EELFLogger intLogger = EELFManager.getInstance().getLogger("InternalLog");\r
51 \r
52     NodeClass() {\r
53         // init on first use\r
54         if (nodesMap == null) {\r
55             reload();\r
56         }\r
57     }\r
58 \r
59     /**\r
60      * Add nodes to the NODES table, when the NODES parameter value is changed. Nodes are only added to the table, they\r
61      * are never deleted.  The node name is normalized to contain the domain (if missing).\r
62      *\r
63      * @param nodes a pipe separated list of the current nodes\r
64      */\r
65     public static void setNodes(String[] nodes) {\r
66         if (nodesMap == null) {\r
67             reload();\r
68         }\r
69         int nextid = 0;\r
70         for (Integer n : nodesMap.values()) {\r
71             if (n >= nextid) {\r
72                 nextid = n + 1;\r
73             }\r
74         }\r
75         // take | separated list, add domain if needed.\r
76 \r
77         for (String node : nodes) {\r
78             node = normalizeNodename(node);\r
79             if (!nodesMap.containsKey(node)) {\r
80                 intLogger.info("..adding " + node + " to NODES with index " + nextid);\r
81                 nodesMap.put(node, nextid);\r
82                 insertNodesToTable(nextid, node);\r
83                 nextid++;\r
84             }\r
85         }\r
86     }\r
87 \r
88     private static void insertNodesToTable(int nextid, String node) {\r
89         try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
90             PreparedStatement ps = conn.prepareStatement(\r
91                 "insert into NODES (NODEID, NAME, ACTIVE) values (?, ?, 1)")) {\r
92             ps.setInt(1, nextid);\r
93             ps.setString(2, node);\r
94             ps.execute();\r
95         } catch (SQLException e) {\r
96             intLogger.error(PROV_0005_DO_INSERT + e.getMessage(), e);\r
97         }\r
98     }\r
99 \r
100     private static void reload() {\r
101         Map<String, Integer> tmpNodesMap = new HashMap<>();\r
102         try (Connection conn = ProvDbUtils.getInstance().getConnection();\r
103             PreparedStatement ps = conn.prepareStatement("select NODEID, NAME from NODES");\r
104             ResultSet rs = ps.executeQuery()) {\r
105             while (rs.next()) {\r
106                 int id = rs.getInt("NODEID");\r
107                 String name = rs.getString("NAME");\r
108                 tmpNodesMap.put(name, id);\r
109             }\r
110         } catch (SQLException e) {\r
111             intLogger.error(PROV_0005_DO_INSERT + e.getMessage(),e);\r
112         }\r
113         nodesMap = tmpNodesMap;\r
114     }\r
115 \r
116     static Integer lookupNodeName(final String name) {\r
117         Integer nodeName = nodesMap.get(name);\r
118         if (nodeName == null) {\r
119             throw new IllegalArgumentException("Invalid node name: " + name);\r
120         }\r
121         return nodeName;\r
122     }\r
123 \r
124     /**\r
125      * Get node names.\r
126      * @param patt pattern to search\r
127      * @return collection of node names\r
128      */\r
129     public static Collection<String> lookupNodeNames(String patt) {\r
130         Collection<String> coll = new TreeSet<>();\r
131         final Set<String> keyset = nodesMap.keySet();\r
132         for (String s : patt.toLowerCase().split(",")) {\r
133             if (s.endsWith("*")) {\r
134                 addNodeToCollection(coll, keyset, s);\r
135             } else if (keyset.contains(s)) {\r
136                 coll.add(s);\r
137             } else if (keyset.contains(normalizeNodename(s))) {\r
138                 coll.add(normalizeNodename(s));\r
139             } else {\r
140                 throw new IllegalArgumentException("Invalid node name: " + s);\r
141             }\r
142         }\r
143         return coll;\r
144     }\r
145 \r
146     private static void addNodeToCollection(Collection<String> coll, Set<String> keyset, String str) {\r
147         str = str.substring(0, str.length() - 1);\r
148         for (String s2 : keyset) {\r
149             if (s2.startsWith(str)) {\r
150                 coll.add(s2);\r
151             }\r
152         }\r
153     }\r
154 \r
155     /**\r
156      * Method to add domain name.\r
157      * @param str nde name string\r
158      * @return normalized node name\r
159      */\r
160     public static String normalizeNodename(String str) {\r
161         if (str != null && str.indexOf('.') <= 0) {\r
162             Parameters param = Parameters.getParameter(Parameters.PROV_DOMAIN);\r
163             if (param != null) {\r
164                 String domain = param.getValue();\r
165                 str += "." + domain;\r
166             }\r
167             return str.toLowerCase();\r
168         } else {\r
169             return str;\r
170         }\r
171 \r
172     }\r
173 \r
174     String lookupNodeID(int node) {\r
175         for (Map.Entry<String, Integer> entry : nodesMap.entrySet()) {\r
176             if (entry.getValue() == node) {\r
177                 return entry.getKey();\r
178             }\r
179         }\r
180         return null;\r
181     }\r
182 }\r