[SDNC-5] Rebase sdnc-core
[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          * @param alarmLog
65          * @param occManager
66          * @throws Exception
67          */
68         public JdbcDBCachedDataSource(BaseDBConfiguration jdbcElem)
69         {
70                         super(jdbcElem);
71         }
72
73         @Override
74         protected void configure(BaseDBConfiguration xmlElem) throws DBConfigException
75         {
76                 BaseDBConfiguration jdbcConfig = (BaseDBConfiguration)xmlElem;
77                 if(jdbcConfig.getConnTimeout() > 0){
78                         this.CONN_REQ_TIMEOUT = jdbcConfig.getConnTimeout();
79                 }
80                 if(jdbcConfig.getRequestTimeout() > 0){
81                                 this.DATA_REQ_TIMEOUT = jdbcConfig.getRequestTimeout();
82                 }
83
84         // set connection pool name
85                 String dbConnectionName = jdbcConfig.getDbConnectionName();
86         super.setDbConnectionName(dbConnectionName);
87         // Configure the JDBC connection
88         dbUserId = jdbcConfig.getDbUserId();
89         if (dbUserId == null)
90         {
91                 String errorMsg =  "Invalid XML contents: JDBCConnection missing dbUserId attribute";
92                 LOGGER.error(AS_CONF_ERROR + errorMsg);
93             throw new DBConfigException(errorMsg);
94         }
95
96         dbPasswd = jdbcConfig.getDbPasswd();
97         if (dbPasswd == null)
98         {
99                 String errorMsg =  "Invalid XML contents: JDBCConnection missing dbPasswd attribute";
100                 LOGGER.error(AS_CONF_ERROR + errorMsg);
101             throw new DBConfigException(errorMsg);
102         }
103         /*
104         dbDriver = jdbcConfig.getDbDriver();
105         if (dbDriver == null)
106         {
107                 String errorMsg =  "Invalid XML contents: JDBCConnection missing dbDriver attribute";
108                 LOGGER.error(AS_CONF_ERROR + errorMsg);
109                 throw new ScpTblUpdateError(errorMsg);
110         }
111         */
112
113         minLimit = jdbcConfig.getDbMinLimit();
114 //        if (minLimit == null)
115 //        {
116 //              String errorMsg =  "Invalid XML contents: JDBC Connection missing minLimit attribute";
117 //              LOGGER.error(AS_CONF_ERROR + errorMsg);
118 //              throw new DBConfigException(errorMsg);
119 //        }
120         maxLimit =  jdbcConfig.getDbMaxLimit();
121 //        if (maxLimit == null)
122 //        {
123 //              String errorMsg =  "Invalid XML contents: JDBC Connection missing maxLimit attribute";
124 //              LOGGER.error(AS_CONF_ERROR + errorMsg);
125 //              throw new DBConfigException(errorMsg);
126 //        }
127         initialLimit =  jdbcConfig.getDbInitialLimit();
128 //        if (initialLimit == null)
129 //        {
130 //              String errorMsg =  "Invalid XML contents: JDBC Connection missing initialLimit attribute";
131 //              LOGGER.error(AS_CONF_ERROR + errorMsg);
132 //              throw new DBConfigException(errorMsg);
133 //        }
134
135         dbUrl = jdbcConfig.getDbUrl();
136         if(dbUrl == null){
137                 String errorMsg =  "Invalid XML contents: JDBCConnection missing dbUrl attribute";
138                 LOGGER.error(AS_CONF_ERROR + errorMsg);
139             throw new DBConfigException(errorMsg);
140         }
141
142                 try {
143                         Driver dr = new com.mysql.jdbc.Driver();
144                         Class clazz = Class.forName("com.mysql.jdbc.Driver") ;
145
146                         PoolProperties p = new PoolProperties();
147                         p.setDriverClassName("com.mysql.jdbc.Driver");
148                         p.setUrl(dbUrl);
149                         p.setUsername(dbUserId);
150                         p.setPassword(dbPasswd);
151                         p.setJmxEnabled(true);
152                         p.setTestWhileIdle(false);
153                         p.setTestOnBorrow(true);
154                         p.setValidationQuery("SELECT 1");
155                         p.setTestOnReturn(false);
156                         p.setValidationInterval(30000);
157                         p.setTimeBetweenEvictionRunsMillis(30000);
158                         p.setInitialSize(initialLimit);
159                         p.setMaxActive(maxLimit);
160                         p.setMaxIdle(maxLimit);
161                         p.setMaxWait(10000);
162                         p.setRemoveAbandonedTimeout(60);
163                         p.setMinEvictableIdleTimeMillis(30000);
164                         p.setMinIdle(minLimit);
165                         p.setLogAbandoned(true);
166                         p.setRemoveAbandoned(true);
167                         p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
168                                         + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
169
170                         DataSource dataSource = new DataSource(p);
171
172                         synchronized(this)
173                         {
174                                 this.ds = dataSource;
175                                 Connection con = null;
176                                 PreparedStatement st = null;
177                                 ResultSet rs = null;
178
179                                 try {
180                                         con = dataSource.getConnection();
181                                         st = con.prepareStatement("Select 1 FROM DUAL");
182                                         rs = st.executeQuery();
183                                 } catch(Exception exc) {
184                                         LOGGER.error(exc.getMessage());
185                                 } finally {
186                                         if(rs != null) rs.close();
187                                         if(st != null) st.close();
188                                         if(con != null) con.close();
189                                 }
190
191                                 initialized = true;
192                                 LOGGER.info("MySQLDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl);
193                         }
194
195 //              } catch (SQLException exc) {
196 //                      initialized = false;
197 //                      StringBuffer sb = new StringBuffer();
198 //                      sb.append("Failed to initialize MySQLDataSource<");
199 //                      sb.append(dbConnectionName).append(">. Reason: ");
200 //                      sb.append(exc.getMessage());
201 //                      LOGGER.error("AS_CONF_ERROR: " + sb.toString());
202 ////                    throw new DBConfigException(e.getMessage());
203                 } catch (Exception exc) {
204                 initialized = false;
205                         StringBuffer sb = new StringBuffer();
206                         sb.append("Failed to initialize MySQLCachedDataSource <");
207                         sb.append(dbConnectionName).append(">. Reason: ");
208                         sb.append(exc.getMessage());
209                         LOGGER.error("AS_CONF_ERROR: " + sb.toString());
210 //              throw new DBConfigException(e.getMessage());
211         }
212     }
213
214         public final String getDbUrl()
215         {
216                 return dbUrl;
217         }
218
219         public final String getDbUserId()
220         {
221                 return dbUserId;
222         }
223
224         public final String getDbPasswd()
225         {
226                 return dbPasswd;
227         }
228
229         public static JdbcDBCachedDataSource createInstance(BaseDBConfiguration config) /*throws Exception*/ {
230                 return new JdbcDBCachedDataSource(config);
231         }
232
233         public String toString(){
234                 return getDbConnectionName();
235         }
236
237         public java.util.logging.Logger getParentLogger()
238                         throws SQLFeatureNotSupportedException {
239                 // TODO Auto-generated method stub
240                 return null;
241         }
242
243         public void cleanUp(){
244                 DataSource dataSource = (DataSource)ds;
245                 dataSource.getPool().purge();
246                 int active = dataSource.getActive();
247                 int size = dataSource.getSize();
248                 dataSource.close(true);
249                 super.cleanUp();
250         }
251
252 }