[SDNC-5] Boron port and bug fixes
[sdnc/core.git] / dblib / provider / src / main / java / org / openecomp / sdnc / sli / resource / dblib / jdbc / JdbcDBCachedDataSource.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openecomp
4  * ================================================================================
5  * Copyright (C) 2016 - 2017 AT&T
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdnc.sli.resource.dblib.jdbc;
22
23 import java.sql.Connection;
24 import java.sql.PreparedStatement;
25 import java.sql.ResultSet;
26 import java.sql.SQLFeatureNotSupportedException;
27
28 import org.apache.tomcat.jdbc.pool.DataSource;
29 import org.apache.tomcat.jdbc.pool.PoolProperties;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 import org.openecomp.sdnc.sli.resource.dblib.CachedDataSource;
34 import org.openecomp.sdnc.sli.resource.dblib.DBConfigException;
35 import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration;
36 import org.openecomp.sdnc.sli.resource.dblib.config.JDBCConfiguration;
37 import com.mysql.jdbc.Driver;
38
39
40 /**
41  * @version $Revision: 1.7 $
42  * Change Log
43  * Author         Date     Comments
44  * ============== ======== ====================================================
45  * Rich Tabedzki
46  */
47
48 public class JdbcDBCachedDataSource extends CachedDataSource
49 {
50         private String dbUserId;
51         private String dbPasswd;
52         private String dbUrl;
53
54         private int minLimit;
55         private int maxLimit;
56         private int initialLimit;
57
58         private static final String AS_CONF_ERROR = "AS_CONF_ERROR: ";
59
60         private static Logger LOGGER = LoggerFactory.getLogger(JdbcDBCachedDataSource.class);
61
62         /**
63          * @param jdbcElem
64          */
65         public JdbcDBCachedDataSource(BaseDBConfiguration jdbcElem)
66         {
67                         super(jdbcElem);
68         }
69
70         @Override
71         protected void configure(BaseDBConfiguration xmlElem) throws DBConfigException
72         {
73                 BaseDBConfiguration jdbcConfig = (BaseDBConfiguration)xmlElem;
74                 if(jdbcConfig.getConnTimeout() > 0){
75                         this.CONN_REQ_TIMEOUT = jdbcConfig.getConnTimeout();
76                 }
77                 if(jdbcConfig.getRequestTimeout() > 0){
78                                 this.DATA_REQ_TIMEOUT = jdbcConfig.getRequestTimeout();
79                 }
80
81         // set connection pool name
82                 String dbConnectionName = jdbcConfig.getDbConnectionName();
83         super.setDbConnectionName(dbConnectionName);
84         // Configure the JDBC connection
85         dbUserId = jdbcConfig.getDbUserId();
86         if (dbUserId == null)
87         {
88                 String errorMsg =  "Invalid XML contents: JDBCConnection missing dbUserId attribute";
89                 LOGGER.error(AS_CONF_ERROR + errorMsg);
90             throw new DBConfigException(errorMsg);
91         }
92
93         dbPasswd = jdbcConfig.getDbPasswd();
94         if (dbPasswd == null)
95         {
96                 String errorMsg =  "Invalid XML contents: JDBCConnection missing dbPasswd attribute";
97                 LOGGER.error(AS_CONF_ERROR + errorMsg);
98             throw new DBConfigException(errorMsg);
99         }
100         /*
101         dbDriver = jdbcConfig.getDbDriver();
102         if (dbDriver == null)
103         {
104                 String errorMsg =  "Invalid XML contents: JDBCConnection missing dbDriver attribute";
105                 LOGGER.error(AS_CONF_ERROR + errorMsg);
106                 throw new ScpTblUpdateError(errorMsg);
107         }
108         */
109
110         minLimit = jdbcConfig.getDbMinLimit();
111 //        if (minLimit == null)
112 //        {
113 //              String errorMsg =  "Invalid XML contents: JDBC Connection missing minLimit attribute";
114 //              LOGGER.error(AS_CONF_ERROR + errorMsg);
115 //              throw new DBConfigException(errorMsg);
116 //        }
117         maxLimit =  jdbcConfig.getDbMaxLimit();
118 //        if (maxLimit == null)
119 //        {
120 //              String errorMsg =  "Invalid XML contents: JDBC Connection missing maxLimit attribute";
121 //              LOGGER.error(AS_CONF_ERROR + errorMsg);
122 //              throw new DBConfigException(errorMsg);
123 //        }
124         initialLimit =  jdbcConfig.getDbInitialLimit();
125 //        if (initialLimit == null)
126 //        {
127 //              String errorMsg =  "Invalid XML contents: JDBC Connection missing initialLimit attribute";
128 //              LOGGER.error(AS_CONF_ERROR + errorMsg);
129 //              throw new DBConfigException(errorMsg);
130 //        }
131
132         dbUrl = jdbcConfig.getDbUrl();
133         if(dbUrl == null){
134                 String errorMsg =  "Invalid XML contents: JDBCConnection missing dbUrl attribute";
135                 LOGGER.error(AS_CONF_ERROR + errorMsg);
136             throw new DBConfigException(errorMsg);
137         }
138
139                 try {
140                         Driver dr = new com.mysql.jdbc.Driver();
141                         Class clazz = Class.forName("com.mysql.jdbc.Driver") ;
142
143                         PoolProperties p = new PoolProperties();
144                         p.setDriverClassName("com.mysql.jdbc.Driver");
145                         p.setUrl(dbUrl);
146                         p.setUsername(dbUserId);
147                         p.setPassword(dbPasswd);
148                         p.setJmxEnabled(true);
149                         p.setTestWhileIdle(false);
150                         p.setTestOnBorrow(true);
151                         p.setValidationQuery("SELECT 1");
152                         p.setTestOnReturn(false);
153                         p.setValidationInterval(30000);
154                         p.setTimeBetweenEvictionRunsMillis(30000);
155                         p.setInitialSize(initialLimit);
156                         p.setMaxActive(maxLimit);
157                         p.setMaxIdle(maxLimit);
158                         p.setMaxWait(10000);
159                         p.setRemoveAbandonedTimeout(60);
160                         p.setMinEvictableIdleTimeMillis(30000);
161                         p.setMinIdle(minLimit);
162                         p.setLogAbandoned(true);
163                         p.setRemoveAbandoned(true);
164                         p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
165                                         + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
166
167                         DataSource dataSource = new DataSource(p);
168
169                         synchronized(this)
170                         {
171                                 this.ds = dataSource;
172                                 Connection con = null;
173                                 PreparedStatement st = null;
174                                 ResultSet rs = null;
175
176                                 try {
177                                         con = dataSource.getConnection();
178                                         st = con.prepareStatement("Select 1 FROM DUAL");
179                                         rs = st.executeQuery();
180                                 } catch(Exception exc) {
181                                         LOGGER.error(exc.getMessage());
182                                 } finally {
183                                         if(rs != null) rs.close();
184                                         if(st != null) st.close();
185                                         if(con != null) con.close();
186                                 }
187
188                                 initialized = true;
189                                 LOGGER.info("MySQLDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl);
190                         }
191
192 //              } catch (SQLException exc) {
193 //                      initialized = false;
194 //                      StringBuffer sb = new StringBuffer();
195 //                      sb.append("Failed to initialize MySQLDataSource<");
196 //                      sb.append(dbConnectionName).append(">. Reason: ");
197 //                      sb.append(exc.getMessage());
198 //                      LOGGER.error("AS_CONF_ERROR: " + sb.toString());
199 ////                    throw new DBConfigException(e.getMessage());
200                 } catch (Exception exc) {
201                 initialized = false;
202                         StringBuffer sb = new StringBuffer();
203                         sb.append("Failed to initialize MySQLCachedDataSource <");
204                         sb.append(dbConnectionName).append(">. Reason: ");
205                         sb.append(exc.getMessage());
206                         LOGGER.error("AS_CONF_ERROR: " + sb.toString());
207 //              throw new DBConfigException(e.getMessage());
208         }
209     }
210
211         public final String getDbUrl()
212         {
213                 return dbUrl;
214         }
215
216         public final String getDbUserId()
217         {
218                 return dbUserId;
219         }
220
221         public final String getDbPasswd()
222         {
223                 return dbPasswd;
224         }
225
226         public static JdbcDBCachedDataSource createInstance(BaseDBConfiguration config) /*throws Exception*/ {
227                 return new JdbcDBCachedDataSource(config);
228         }
229
230         public String toString(){
231                 return getDbConnectionName();
232         }
233
234         public java.util.logging.Logger getParentLogger()
235                         throws SQLFeatureNotSupportedException {
236                 // TODO Auto-generated method stub
237                 return null;
238         }
239
240         public void cleanUp(){
241                 DataSource dataSource = (DataSource)ds;
242                 dataSource.getPool().purge();
243                 int active = dataSource.getActive();
244                 int size = dataSource.getSize();
245                 dataSource.close(true);
246                 super.cleanUp();
247         }
248
249 }