Update groupId to org.onap.ccsdk.sli
[ccsdk/sli/core.git] / dblib / provider / src / main / java / org / onap / ccsdk / sli / core / dblib / jdbc / JdbcDbResourceManagerFactory.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * onap
4  * ================================================================================
5  * Copyright (C) 2016 - 2017 ONAP
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.onap.ccsdk.sli.core.dblib.jdbc;
22
23
24 import java.sql.SQLException;
25 import java.util.Arrays;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Set;
29 import java.util.concurrent.Callable;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.Executors;
33 import java.util.concurrent.FutureTask;
34
35 import org.onap.ccsdk.sli.core.dblib.CachedDataSource;
36 import org.onap.ccsdk.sli.core.dblib.CachedDataSourceFactory;
37 import org.onap.ccsdk.sli.core.dblib.DBResourceManager;
38 import org.onap.ccsdk.sli.core.dblib.DataSourceComparator;
39 import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool;
40 import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration;
41 import org.onap.ccsdk.sli.core.dblib.factory.AbstractResourceManagerFactory;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * @version $Revision: 1.6 $
47  * Change Log
48  * Author         Date     Comments
49  * ============== ======== ====================================================
50  * Rich Tabedzki
51  */
52 public class JdbcDbResourceManagerFactory extends AbstractResourceManagerFactory {
53         private static Logger LOGGER = LoggerFactory.getLogger(JdbcDbResourceManagerFactory.class );
54         private JdbcDbResourceManagerFactory(){
55
56         }
57
58         class MyFutureTask extends FutureTask<CachedDataSource>
59         {
60
61                 public MyFutureTask(Callable<CachedDataSource> result) {
62                         super(result);
63                 }
64
65         }
66
67         public CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager manager, String sourceName) throws SQLException
68         {
69                 // here create the data sources objects
70                 JDBCConfiguration[] list = dbConfig.getJDBCbSourceArray();
71                 CachedDataSource[] cachedDS = new CachedDataSource[1];
72
73                 for(int i=0, max=list.length; i<max; i++){
74                         if(!sourceName.equals(list[i].getDbConnectionName()))
75                                 continue;
76
77                         JDBCConfiguration config = list[i];
78                         CachedDataSource dataSource = CachedDataSourceFactory.createDataSource(config);
79                         cachedDS[0] = dataSource;
80                 }
81                 return cachedDS;
82         }
83
84         public CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager manager) /* throws Exception */ {
85
86                 ExecutorService threadExecutor = Executors.newFixedThreadPool(2);
87                 // here create the data sources objects
88                 JDBCConfiguration[] list = dbConfig.getJDBCbSourceArray();
89
90                 MyFutureTask[] futures = new MyFutureTask[list.length];
91                 final Set<DBInitTask> tasks = new HashSet<DBInitTask>();
92                 if(LOGGER.isDebugEnabled()) {
93                         LOGGER.debug("Creating " + list.length + " datasources.");
94                 }
95
96                 for(int i=0, max=list.length; i<max; i++){
97                         JDBCConfiguration config = list[i];
98
99                         DBInitTask task = new DBInitTask(config, tasks);
100                         tasks.add(task);
101                         futures[i] = new MyFutureTask(task);
102                 }
103
104                 try {
105                         synchronized(tasks){
106                                 for(int i=0, max=list.length; i<max; i++){
107                                         if(LOGGER.isDebugEnabled())
108                                                 LOGGER.debug("Starting executor tasks.");
109                                         threadExecutor.execute(futures[i]);
110                                 }
111                                 // the timeout param is set is seconds.
112                                 long timeout = ((dbConfig.getTimeout() <= 0) ? 60L : dbConfig.getTimeout());
113                                 LOGGER.debug("Timeout set to " +timeout+" seconds");
114                                 timeout *= 1000;
115                                 // the timeout param is set is seconds, hence it needs to be multiplied by 1000.
116                                 tasks.wait(timeout);
117                                 if(LOGGER.isDebugEnabled())
118                                         LOGGER.debug("initDBResourceManager wait completed.");
119                         }
120                 } catch(Exception exc) {
121                         LOGGER.error("Failed to initialize JndiCachedDataSource. Reason: ", exc);
122                 }
123
124                 if(threadExecutor != null){
125                         try {
126                                 threadExecutor.shutdown();
127                         } catch(Exception exc){}
128                 }
129
130                 CachedDataSource[] cachedDS = new CachedDataSource[futures.length];
131
132                 boolean initialized = false;
133                 for(int i=0; i<futures.length; i++){
134                         Object obj = null;
135                         if(futures[i].isDone()){
136                                 try {
137                                         obj = futures[i].get();
138                                         if(obj instanceof CachedDataSource){
139                                                 cachedDS[i] = (CachedDataSource)obj;
140                                                 initialized |= cachedDS[i].isInitialized();
141                                                 if(cachedDS[i].isInitialized())
142                                                         LOGGER.info("DataSource "+list[i].getDbConnectionName()+" initialized successfully");
143                                                 else
144                                                         LOGGER.error("DataSource "+list[i].getDbConnectionName()+" initialization failed");
145                                         } else {
146                                                 if(obj == null) {
147                                                         LOGGER.warn("DataSource " + i + " initialization failed. Returned object is null");
148                                                 } else {
149                                                         LOGGER.warn("DataSource " + i + " initialization failed. Returned object is " + obj.getClass().getName());
150                                                 }
151                                         }
152                                 } catch (InterruptedException exc) {
153                                         LOGGER.error("DataSource "+list[i].getDbConnectionName()+" initialization failed", exc);
154                                 } catch (ExecutionException exc) {
155                                         LOGGER.error("DataSource "+list[i].getDbConnectionName()+" initialization failed", exc);
156                                 } catch (Exception exc) {
157                                         LOGGER.error("DataSource "+list[i].getDbConnectionName()+" initialization failed", exc);
158                                 }
159                         } else {
160                                 try {
161                                         obj = futures[i].get();
162                                         if(obj instanceof CachedDataSource){
163                                                 LOGGER.warn("DataSource "+((CachedDataSource)obj).getDbConnectionName()+" failed");
164                                         } else {
165                                                 if(obj == null) {
166                                                         LOGGER.warn("DataSource " + i + " initialization failed. Returned object is null");
167                                                 } else {
168                                                         LOGGER.warn("DataSource " + i + " initialization failed. Returned object is " + obj.getClass().getName());
169                                                 }
170                                         }
171                                 } catch (Exception exc) {
172                                         LOGGER.error("DataSource "+list[i].getDbConnectionName()+" initialization failed", exc);
173                                 }
174                         }
175                 }
176
177                 if(!initialized){
178                         new Error("Failed to initialize DB Library.");
179                 }
180                 return cachedDS;
181         }
182
183         public static AbstractResourceManagerFactory createIntstance() {
184                 return new JdbcDbResourceManagerFactory();
185         }
186 }