Fix sonar issues in dmaap-dbcpi
[dmaap/dbcapi.git] / 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                 }
165             }
166
167             public Dmaap get() {
168                 return (dmaap);
169             }
170
171             public void update(Dmaap nd) {
172                 dmaap.setVersion(nd.getVersion());
173                 dmaap.setTopicNsRoot(nd.getTopicNsRoot());
174                 dmaap.setDmaapName(nd.getDmaapName());
175                 dmaap.setDrProvUrl(nd.getDrProvUrl());
176                 dmaap.setBridgeAdminTopic(nd.getBridgeAdminTopic());
177                 dmaap.setLoggingUrl(nd.getLoggingUrl());
178                 dmaap.setNodeKey(nd.getNodeKey());
179                 dmaap.setAccessKeyOwner(nd.getAccessKeyOwner());
180             }
181         };
182         initMemoryDatabase();
183     }
184
185     private static void databaseResourceInit() {
186         appLogger.info("Data from database");
187         try {
188             LoadSchema.upgrade();
189         } catch (Exception e) {
190             appLogger.warn("Problem updating DB schema", e);
191         }
192         try {
193             dmaap = new DBSingleton<>(Dmaap.class, "dmaap");
194             TableHandler.setSpecialCase("topic", "replication_case", new TopicReplicationTypeHandler());
195             TableHandler.setSpecialCase("mirror_maker", "topics", new MirrorTopicsHandler());
196             initDatabase();
197         } catch (Exception e) {
198             errorLogger.error("Error initializing database access " + e, e);
199             System.exit(1);
200         }
201     }
202
203     private static class MirrorTopicsHandler implements DBFieldHandler.SqlOp {
204
205         public Object get(ResultSet rs, int index) throws Exception {
206             String val = rs.getString(index);
207             if (val == null) {
208                 return (null);
209             }
210             List<String> rv = new ArrayList<>();
211             for (String s : val.split(",")) {
212                 rv.add(new String(s));
213             }
214             return (rv);
215         }
216
217         public void set(PreparedStatement ps, int index, Object val) throws Exception {
218             if (val == null) {
219                 ps.setString(index, null);
220                 return;
221             }
222             @SuppressWarnings("unchecked")
223             List<String> xv = (List<String>) val;
224             StringBuilder sb = new StringBuilder();
225             String sep = "";
226             for (Object o : xv) {
227                 String rv = (String) o;
228                 sb.append(sep).append(DBFieldHandler.fesc(rv));
229                 sep = ",";
230             }
231             ps.setString(index, sb.toString());
232         }
233     }
234
235     private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp {
236
237         public Object get(ResultSet rs, int index) throws Exception {
238             int val = rs.getInt(index);
239
240             return (ReplicationType.valueOf(val));
241         }
242
243         public void set(PreparedStatement ps, int index, Object val) throws Exception {
244             if (val == null) {
245                 ps.setInt(index, 0);
246                 return;
247             }
248             @SuppressWarnings("unchecked")
249             ReplicationType rep = (ReplicationType) val;
250             ps.setInt(index, rep.getValue());
251         }
252     }
253
254     private static void initMemoryDatabase() {
255         dcaeLocations = new HashMap<>();
256         dr_nodes = new HashMap<>();
257         dr_pubs = new HashMap<>();
258         dr_subs = new HashMap<>();
259         mr_clients = new HashMap<>();
260         mr_clusters = new HashMap<>();
261         feeds = new HashMap<>();
262         topics = new HashMap<>();
263         mirrors = new HashMap<>();
264     }
265
266     private static void initDatabase() throws Exception {
267         dcaeLocations = new DBMap<>(DcaeLocation.class, "dcae_location", "dcae_location_name");
268         dr_nodes = new DBMap<>(DR_Node.class, "dr_node", "fqdn");
269         dr_pubs = new DBMap<>(DR_Pub.class, "dr_pub", "pub_id");
270         dr_subs = new DBMap<>(DR_Sub.class, "dr_sub", "sub_id");
271         mr_clients = new DBMap<>(MR_Client.class, "mr_client", "mr_client_id");
272         mr_clusters = new DBMap<>(MR_Cluster.class, "mr_cluster", "dcae_location_name");
273         feeds = new DBMap<>(Feed.class, "feed", "feed_id");
274         topics = new DBMap<>(Topic.class, "topic", "fqtn");
275         mirrors = new DBMap<>(MirrorMaker.class, "mirror_maker", "mm_name");
276     }
277
278     private static void determineDatabaseType() {
279         DmaapConfig dmaapConfig = (DmaapConfig) DmaapConfig.getConfig();
280         String isPgSQLset = dmaapConfig.getProperty("UsePGSQL", "false");
281         databaseType = isPgSQLset.equalsIgnoreCase("true") ? DBType.PGSQL : DBType.MEMORY;
282     }
283 }