DMAAP-83 Initial code import
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / aaf / database / ConnWrapper.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dmaap
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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.dmaap.dbcapi.aaf.database;
22
23 import java.sql.*;
24
25
26 public abstract class ConnWrapper<T, U> {
27         protected Connection c;
28         protected PreparedStatement ps;
29         protected ResultSet     rs;
30         protected abstract T run(U u) throws Exception;
31         public T protect(ConnectionFactory cf, U u) throws DBException {
32                 try {
33                         try {
34                                 return(attempt(cf, u, false));
35                         } catch (SQLException sqle) {
36                                 return(attempt(cf, u, true));
37                         }
38                 } catch (RuntimeException rte) {
39                         throw rte;
40                 } catch (Exception e) {
41                         throw new DBException(e);
42                 }
43         }
44         private T attempt(ConnectionFactory cf, U u, boolean fresh) throws Exception {
45                 c = null;
46                 ps = null;
47                 rs = null;
48                 try {
49                         c = cf.get(fresh);
50                         T ret = run(u);
51                         cf.release(c);
52                         c = null;
53                         return(ret);
54                 } finally {
55                         if (rs != null) { try { rs.close(); } catch (Exception e) {}}
56                         rs = null;
57                         if (ps != null) { try { ps.close(); } catch (Exception e) {}}
58                         ps = null;
59                         if (c != null) { try { c.close(); } catch (Exception e) {}}
60                         c = null;
61                 }
62         }
63 }