2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 Nordix Foundation.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.dmaap.datarouter.provisioning.utils;
23 import static java.lang.System.exit;
25 import com.att.eelf.configuration.EELFLogger;
26 import com.att.eelf.configuration.EELFManager;
28 import java.io.FileReader;
29 import java.io.LineNumberReader;
30 import java.sql.Connection;
31 import java.sql.DatabaseMetaData;
32 import java.sql.ResultSet;
33 import java.sql.SQLException;
34 import java.sql.Statement;
35 import java.util.HashSet;
36 import java.util.Properties;
38 import javax.sql.DataSource;
39 import org.apache.commons.dbcp2.BasicDataSource;
40 import org.onap.dmaap.datarouter.provisioning.ProvRunner;
42 public class ProvDbUtils {
44 private static EELFLogger intLogger = EELFManager.getInstance().getLogger("InternalLog");
45 private static DataSource dataSource;
46 private static ProvDbUtils provDbUtils;
48 private ProvDbUtils() {
51 public static ProvDbUtils getInstance() {
52 if (provDbUtils == null) {
54 provDbUtils = new ProvDbUtils();
55 dataSource = setupDataSource(ProvRunner.getProvProperties());
56 } catch (ClassNotFoundException e) {
57 intLogger.error("PROV9010: Failed to load DB Driver Class: " + e.getMessage(), e);
64 private static DataSource setupDataSource(Properties props) throws ClassNotFoundException {
65 intLogger.info("PROV9009: Setting up DB dataSource");
66 Class.forName((String) props.get("org.onap.dmaap.datarouter.db.driver"));
67 BasicDataSource dataSource = new BasicDataSource();
68 dataSource.setUrl((String) props.get("org.onap.dmaap.datarouter.db.url"));
69 dataSource.setUsername(getValue(props, "org.onap.dmaap.datarouter.db.login"));
70 dataSource.setPassword(getValue(props, "org.onap.dmaap.datarouter.db.password"));
71 dataSource.setMinIdle(5);
72 dataSource.setMaxIdle(15);
73 dataSource.setMaxOpenPreparedStatements(100);
77 private static String getValue(final Properties props, final String value) {
78 String prop = (String) props.get(value);
79 if (prop != null && prop.matches("[$][{].*[}]$")) {
80 return System.getenv(prop.substring(2, prop.length() - 1));
85 public Connection getConnection() throws SQLException {
86 return dataSource.getConnection();
89 public boolean initProvDB() {
90 final String[] expectedTables = {
91 "FEEDS", "FEED_ENDPOINT_ADDRS", "FEED_ENDPOINT_IDS", "PARAMETERS",
92 "SUBSCRIPTIONS", "LOG_RECORDS", "INGRESS_ROUTES", "EGRESS_ROUTES",
93 "NETWORK_ROUTES", "NODESETS", "NODES", "GROUPS"
95 try (Connection connection = getConnection()) {
96 Set<String> actualTables = getTableSet(connection);
97 boolean initialize = false;
98 for (String tableName : expectedTables) {
99 initialize |= !actualTables.contains(tableName);
102 intLogger.info("PROV9001: First time startup; The database is being initialized.");
103 runInitScript(connection, 1);
105 } catch (SQLException e) {
106 intLogger.error("PROV9000: The database credentials are not working: " + e.getMessage(), e);
113 * Get a set of all table names in the DB.
115 * @param connection a DB connection
116 * @return the set of table names
118 private Set<String> getTableSet(Connection connection) {
119 Set<String> tables = new HashSet<>();
121 DatabaseMetaData md = connection.getMetaData();
122 ResultSet rs = md.getTables(null, null, "%", null);
125 tables.add(rs.getString("TABLE_NAME").toUpperCase());
129 } catch (SQLException e) {
130 intLogger.error("PROV9010: Failed to get TABLE data from DB: " + e.getMessage(), e);
136 * Initialize the tables by running the initialization scripts located in the directory specified by the property
137 * <i>org.onap.dmaap.datarouter.provserver.dbscripts</i>. Scripts have names of the form
140 * @param connection a DB connection
141 * @param scriptId the number of the sql_init_NN.sql script to run
143 private void runInitScript(Connection connection, int scriptId) {
144 String scriptDir = ProvRunner.getProvProperties().getProperty("org.onap.dmaap.datarouter.provserver.dbscripts");
145 String scriptFile = String.format("%s/sql_init_%02d.sql", scriptDir, scriptId);
146 if (!(new File(scriptFile)).exists()) {
147 intLogger.error("PROV9005 Failed to load sql script from : " + scriptFile);
150 try (LineNumberReader lineReader = new LineNumberReader(new FileReader(scriptFile));
151 Statement statement = connection.createStatement()) {
152 StringBuilder strBuilder = new StringBuilder();
154 while ((line = lineReader.readLine()) != null) {
155 if (!line.startsWith("--")) {
157 strBuilder.append(line);
158 executeDdlStatement(statement, strBuilder, line);
161 strBuilder.setLength(0);
162 } catch (Exception e) {
163 intLogger.error("PROV9002 Error when initializing table: " + e.getMessage(), e);
169 private void executeDdlStatement(Statement statement, StringBuilder strBuilder, String line) throws SQLException {
170 if (line.endsWith(";")) {
171 String sql = strBuilder.toString();
172 strBuilder.setLength(0);
173 statement.execute(sql);