Fixed Bugs Detected by SonarCloud
[holmes/common.git] / holmes-actions / src / main / java / org / onap / holmes / common / utils / DbDaoUtil.java
1 /**\r
2  * Copyright 2017-2020 ZTE Corporation.\r
3  * <p>\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  * <p>\r
8  * http://www.apache.org/licenses/LICENSE-2.0\r
9  * <p>\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 package org.onap.holmes.common.utils;\r
17 \r
18 import io.dropwizard.db.DataSourceFactory;\r
19 import io.dropwizard.jdbi.DBIFactory;\r
20 import io.dropwizard.setup.Environment;\r
21 import lombok.extern.slf4j.Slf4j;\r
22 import org.jvnet.hk2.annotations.Service;\r
23 import org.skife.jdbi.v2.DBI;\r
24 import org.skife.jdbi.v2.Handle;\r
25 \r
26 import javax.annotation.PostConstruct;\r
27 import javax.inject.Inject;\r
28 import javax.inject.Singleton;\r
29 \r
30 @Singleton\r
31 @Service\r
32 @Slf4j\r
33 public class DbDaoUtil {\r
34 \r
35     private DBI jdbi;\r
36     @Inject\r
37     private Environment environmentProvider;\r
38     @Inject\r
39     private DataSourceFactory dataSourceFactoryProvider;\r
40 \r
41     private DBIFactory factory = new DBIFactory();\r
42 \r
43     @PostConstruct\r
44     public synchronized void init() {\r
45         if (jdbi == null) {\r
46             jdbi = factory.build(environmentProvider, dataSourceFactoryProvider, "postgres");\r
47         }\r
48     }\r
49 \r
50     public <K> K getDao(Class<K> clazz) {\r
51         try {\r
52             return jdbi.open(clazz);\r
53         } catch (Exception e) {\r
54             log.warn("get object instance of Dao error.", e);\r
55         }\r
56         return null;\r
57     }\r
58 \r
59     public Handle getHandle() {\r
60         try {\r
61             return jdbi.open();\r
62         } catch (Exception e) {\r
63             log.warn("get object instance of Dao error.", e);\r
64         }\r
65         return null;\r
66     }\r
67 \r
68     public void close(Object obj) {\r
69         if (obj != null) {\r
70             try {\r
71                 jdbi.close(obj);\r
72             } catch (Exception e) {\r
73                 log.warn("close jdbi connection error.", e);\r
74             }\r
75         }\r
76     }\r
77 \r
78     public <T> T getJdbiDaoByOnDemand(Class<T> daoClazz) {\r
79 \r
80         return jdbi.onDemand(daoClazz);\r
81 \r
82     }\r
83 \r
84     public <T> T getJdbiDaoByOpen(Class<T> daoClazz) {\r
85 \r
86         return jdbi.open(daoClazz);\r
87 \r
88     }\r
89 }\r