Allow storing db.user and db.pass in environment variables
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / database / ConnectionFactory.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dmaap
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 IBM.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.dmaap.dbcapi.database;
23
24 import java.sql.*;
25 import java.util.*;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29
30 import java.util.concurrent.TimeUnit;
31 import org.onap.dmaap.dbcapi.util.DmaapConfig;
32
33 public class ConnectionFactory  {
34          static final EELFLogger logger = EELFManager.getInstance().getLogger( ConnectionFactory.class );
35          static final EELFLogger appLogger = EELFManager.getInstance().getApplicationLogger();
36          static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
37          static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
38          static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
39          static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
40          static final EELFLogger serverLogger = EELFManager.getInstance().getServerLogger();
41          static final int PREPARE_PSQL_CONNECTION_ATTEMPTS = 5;
42
43         static {
44                 try {
45                         Class.forName("org.postgresql.Driver");
46                 } catch (Exception e) {
47                         logger.error("Unable to load postgres driver " + e, e);
48                 }
49         }
50         private static ConnectionFactory instance = new ConnectionFactory();
51         private String  host;
52         private String  dbname;
53         private String  dbuser;
54         private String  dbcr;
55         private String  schema;
56         
57         public ConnectionFactory() {
58                 Properties p = DmaapConfig.getConfig();
59                 host = p.getProperty("DB.host", "dcae-pstg-write-ftl.domain.notset.com");
60                 dbname = p.getProperty("DB.name", "dmaap");
61                 dbuser = getValue(p, "DB.user", "dmaap_admin");
62                 dbcr = getValue(p, "DB.cred", "test234-ftl");
63                 schema = p.getProperty("DB.schema", "public");
64         }
65
66         private static String getValue(final Properties props, final String value, final String defaultValue) {
67                 String prop = props.getProperty(value, defaultValue);
68                 if (prop != null && prop.matches("[$][{].*[}]$")) {
69                         return System.getenv(prop.substring(2, prop.length() - 1));
70                 }
71                 return prop;
72         }
73
74         public static ConnectionFactory getDefaultInstance() {
75                 return(instance);
76         }
77         private Connection[] pool = new Connection[5];
78         private int     cur;
79         public Connection get(boolean fresh) throws SQLException {
80                 if (!fresh) {
81                         synchronized(this) {
82                                 if (cur > 0) {
83                                         return(pool[--cur]);
84                                 }
85                         }
86                 }
87                 Properties p = new Properties();
88                 p.put("user", dbuser);
89                 p.put("password", dbcr);
90                 for (int i=1; i<PREPARE_PSQL_CONNECTION_ATTEMPTS; i++){
91                         try{
92                                 return(DriverManager.getConnection("jdbc:postgresql://" + host + "/" + dbname, p));
93                         }catch(SQLException e){
94                                 logger.error("Unable to connect to the postgres server. " + i + "attempt failed. ", e);
95                                 waitFor(1);
96                         }
97                 }
98                 return(DriverManager.getConnection("jdbc:postgresql://" + host + "/" + dbname, p));
99         }
100         public String getSchema() {
101                 return(schema);
102         }
103         public void release(Connection c) {
104                 synchronized(this) {
105                         if (cur < pool.length) {
106                                 pool[cur++] = c;
107                                 return;
108                         }
109                 }
110                 try { 
111                         c.close(); 
112                 } catch (Exception e) {
113                         logger.error("Error", e);
114                 }
115         }
116         private void waitFor(long seconds){
117                 try {
118                         TimeUnit.SECONDS.sleep(seconds);
119                 } catch (InterruptedException e) {
120                         logger.debug("Waiting interrupted. ", e);
121                         Thread.currentThread().interrupt();
122                 }
123         }
124 }