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