[DMAAP-BC] Consolidate bus controller repos
[dmaap/buscontroller.git] / dmaap-bc / src / main / java / org / onap / dmaap / dbcapi / database / DatabaseClass.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dmaap
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  *
7  * Modifications Copyright (C) 2019 IBM.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.dmaap.dbcapi.database;
24
25 import java.util.*;
26 import java.sql.*;
27
28 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
29 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
30 import org.onap.dmaap.dbcapi.model.*;
31 import org.onap.dmaap.dbcapi.util.DmaapConfig;
32 import org.onap.dmaap.dbcapi.util.Singleton;
33
34
35 public class DatabaseClass extends BaseLoggingClass {
36
37     private static Singleton<Dmaap> dmaap;
38     private static Map<String, DcaeLocation> dcaeLocations;
39     private static Map<String, DR_Node> dr_nodes;
40     private static Map<String, DR_Pub> dr_pubs;
41     private static Map<String, DR_Sub> dr_subs;
42     private static Map<String, MR_Client> mr_clients;
43     private static Map<String, MR_Cluster> mr_clusters;
44     private static Map<String, Feed> feeds;
45     private static Map<String, Topic> topics;
46     private static Map<String, MirrorMaker> mirrors;
47
48     private static long lastTime = 0L;
49     private static DBType databaseType;
50
51     private enum DBType {
52         PGSQL, MEMORY
53     }
54
55     public static Singleton<Dmaap> getDmaap() {
56         return dmaap;
57     }
58
59
60     public static Map<String, DcaeLocation> getDcaeLocations() {
61         return dcaeLocations;
62     }
63
64     public static Map<String, DR_Node> getDr_nodes() {
65         return dr_nodes;
66     }
67
68     public static Map<String, DR_Sub> getDr_subs() {
69         return dr_subs;
70     }
71
72     public static Map<String, DR_Pub> getDr_pubs() {
73         return dr_pubs;
74     }
75
76     public static Map<String, MR_Client> getMr_clients() {
77         return mr_clients;
78     }
79
80
81     public static Map<String, MR_Cluster> getMr_clusters() {
82         return mr_clusters;
83     }
84
85     public static Map<String, Feed> getFeeds() {
86         return feeds;
87     }
88
89     public static Map<String, Topic> getTopics() {
90         return topics;
91     }
92
93     public static Map<String, MirrorMaker> getMirrorMakers() {
94         return mirrors;
95     }
96
97     static {
98         try {
99             appLogger.info("begin static initialization");
100             appLogger.info("initializing dmaap");
101             determineDatabaseType();
102
103             switch (databaseType) {
104                 case PGSQL:
105                     databaseResourceInit();
106                     break;
107                 case MEMORY:
108                     inMemoryResourceInit();
109                     break;
110             }
111
112             dmaap.init(new Dmaap.DmaapBuilder().setVer("0").setTnr("").setDn("").setDpu("").setLu("").setBat("").setNk("").setAko("").createDmaap());
113             // force initial read from DB, if it exists
114             @SuppressWarnings("unused")
115             Dmaap dmx = dmaap.get();
116
117             // old code in this spot would read from properties file as part of init.
118             // but all those properties are now set via /dmaap API
119
120         } catch (Exception e) {
121             errorLogger.error("Error", e);
122             errorLogger.error(DmaapbcLogMessageEnum.DB_UPDATE_ERROR, e.getMessage());
123         }
124
125     }
126
127     public static synchronized String getNextClientId() {
128
129         long id = System.currentTimeMillis();
130         if (id <= lastTime) {
131             id = lastTime + 1;
132         }
133         lastTime = id;
134         return Long.toString(id);
135     }
136
137     public static synchronized void clearDatabase() {
138         switch (databaseType) {
139             case PGSQL:
140                 try {
141                     initDatabase();
142                 } catch (Exception e) {
143                     errorLogger.error("Error initializing database access " + e, e);
144                 }
145                 break;
146             case MEMORY:
147                 initMemoryDatabase();
148                 break;
149         }
150     }
151
152     private static void inMemoryResourceInit() {
153         appLogger.info("Data from memory");
154         dmaap = new Singleton<Dmaap>() {
155             private Dmaap dmaap;
156
157             public void remove() {
158                 dmaap = null;
159             }
160
161             public void init(Dmaap val) {
162                 if (dmaap == null) {
163                     dmaap = val;
164                 } else {
165                     update(val);
166                 }
167             }
168
169             public Dmaap get() {
170                 return (dmaap);
171             }
172
173             public void update(Dmaap nd) {
174                 dmaap.setVersion(nd.getVersion());
175                 dmaap.setTopicNsRoot(nd.getTopicNsRoot());
176                 dmaap.setDmaapName(nd.getDmaapName());
177                 dmaap.setDrProvUrl(nd.getDrProvUrl());
178                 dmaap.setBridgeAdminTopic(nd.getBridgeAdminTopic());
179                 dmaap.setLoggingUrl(nd.getLoggingUrl());
180                 dmaap.setNodeKey(nd.getNodeKey());
181                 dmaap.setAccessKeyOwner(nd.getAccessKeyOwner());
182             }
183         };
184         initMemoryDatabase();
185     }
186
187     private static void databaseResourceInit() {
188         appLogger.info("Data from database");
189         try {
190             LoadSchema.loadSchema();
191         } catch (Exception e) {
192             appLogger.warn("Problem updating DB schema", e);
193         }
194         try {
195             Thread.sleep(5000);
196             dmaap = new DBSingleton<>(Dmaap.class, "dmaap");
197             TableHandler.setSpecialCase("topic", "replication_case", new TopicReplicationTypeHandler());
198             TableHandler.setSpecialCase("mirror_maker", "topics", new MirrorTopicsHandler());
199             initDatabase();
200         } catch (Exception e) {
201             errorLogger.error("Error initializing database access " + e, e);
202             System.exit(1);
203         }
204     }
205
206     private static class MirrorTopicsHandler implements DBFieldHandler.SqlOp {
207
208         public Object get(ResultSet rs, int index) throws Exception {
209             String val = rs.getString(index);
210             if (val == null) {
211                 return (null);
212             }
213             List<String> rv = new ArrayList<>();
214             for (String s : val.split(",")) {
215                 rv.add(new String(s));
216             }
217             return (rv);
218         }
219
220         public void set(PreparedStatement ps, int index, Object val) throws Exception {
221             if (val == null) {
222                 ps.setString(index, null);
223                 return;
224             }
225             @SuppressWarnings("unchecked")
226             List<String> xv = (List<String>) val;
227             StringBuilder sb = new StringBuilder();
228             String sep = "";
229             for (Object o : xv) {
230                 String rv = (String) o;
231                 sb.append(sep).append(DBFieldHandler.fesc(rv));
232                 sep = ",";
233             }
234             ps.setString(index, sb.toString());
235         }
236     }
237
238     private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp {
239
240         public Object get(ResultSet rs, int index) throws Exception {
241             int val = rs.getInt(index);
242
243             return (ReplicationType.valueOf(val));
244         }
245
246         public void set(PreparedStatement ps, int index, Object val) throws Exception {
247             if (val == null) {
248                 ps.setInt(index, 0);
249                 return;
250             }
251             @SuppressWarnings("unchecked")
252             ReplicationType rep = (ReplicationType) val;
253             ps.setInt(index, rep.getValue());
254         }
255     }
256
257     private static void initMemoryDatabase() {
258         dcaeLocations = new HashMap<>();
259         dr_nodes = new HashMap<>();
260         dr_pubs = new HashMap<>();
261         dr_subs = new HashMap<>();
262         mr_clients = new HashMap<>();
263         mr_clusters = new HashMap<>();
264         feeds = new HashMap<>();
265         topics = new HashMap<>();
266         mirrors = new HashMap<>();
267     }
268
269     private static void initDatabase() throws Exception {
270         dcaeLocations = new DBMap<>(DcaeLocation.class, "dcae_location", "dcae_location_name");
271         dr_nodes = new DBMap<>(DR_Node.class, "dr_node", "fqdn");
272         dr_pubs = new DBMap<>(DR_Pub.class, "dr_pub", "pub_id");
273         dr_subs = new DBMap<>(DR_Sub.class, "dr_sub", "sub_id");
274         mr_clients = new DBMap<>(MR_Client.class, "mr_client", "mr_client_id");
275         mr_clusters = new DBMap<>(MR_Cluster.class, "mr_cluster", "dcae_location_name");
276         feeds = new DBMap<>(Feed.class, "feed", "feed_id");
277         topics = new DBMap<>(Topic.class, "topic", "fqtn");
278         mirrors = new DBMap<>(MirrorMaker.class, "mirror_maker", "mm_name");
279     }
280
281     private static void determineDatabaseType() {
282         DmaapConfig dmaapConfig = (DmaapConfig) DmaapConfig.getConfig();
283         String isPgSQLset = dmaapConfig.getProperty("UsePGSQL", "false");
284         databaseType = isPgSQLset.equalsIgnoreCase("true") ? DBType.PGSQL : DBType.MEMORY;
285     }
286 }