Release patch 2.0.4
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / database / DBFieldHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dmaap
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  *
7  * Modifications Copyright (C) 2019 IBM.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.dmaap.dbcapi.database;
24
25 import java.lang.reflect.*;
26 import java.sql.*;
27 import java.util.*;
28
29 import org.onap.dmaap.dbcapi.model.*;
30
31
32 import com.att.eelf.configuration.EELFLogger;
33 import com.att.eelf.configuration.EELFManager;
34
35 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
36
37
38 public class DBFieldHandler     {
39         static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();       
40
41         public DBFieldHandler(Class<?> c, String fieldname, int fieldnum) throws Exception {
42                 this(c, fieldname, fieldnum, null);
43         }
44         public DBFieldHandler(Class<?> c, String fieldname, int fieldnum, SqlOp op) throws Exception {
45                 this.fieldnum = fieldnum;
46                 StringBuilder sb = new StringBuilder();
47                 for (String s: fieldname.split("_")) {  
48                         sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1));
49                 }
50                 String camelcase = sb.toString();
51                 try {
52                         objget = c.getMethod("is" + camelcase);
53                 } catch (Exception e) {
54                         errorLogger.warn("No 'is' method for " + c.getName() + " so trying 'get' method");
55                         objget = c.getMethod("get" + camelcase);
56                 }
57                 objset = c.getMethod("set" + camelcase, objget.getReturnType());
58                 sqlop = op;
59                 if (sqlop != null) {
60                         return;
61                 }
62                 Class<?> x = objget.getReturnType();
63                 if (x.isEnum()) {
64                         sqlop = new EnumSql(x);
65                         return;
66                 }
67                 sqlop = sqltypes.get(x.getName());
68                 if (sqlop != null) {
69                         return;
70                 }
71                 errorLogger.error(DmaapbcLogMessageEnum.DB_NO_FIELD_HANDLER,  c.getName(),  fieldname,  Integer.toString(fieldnum),  x.getName());
72         }
73         
74         public static interface SqlOp   {
75                 public Object get(ResultSet rs, int index) throws Exception;
76                 public void set(PreparedStatement ps, int index, Object value) throws Exception;
77         }
78         private static class    AofString implements SqlOp {
79                 public Object get(ResultSet rs, int index) throws Exception {
80                         String val = rs.getString(index);
81                         if (val == null) {
82                                 return(null);
83                         }
84                         String[] ret = val.split(",");
85                         for (int i = 0; i < ret.length; i++) {
86                                 ret[i] = funesc(ret[i]);
87                         }
88                         return(ret);
89                 }
90                 public void set(PreparedStatement ps, int index, Object x) throws Exception {
91                         String[] val = (String[])x;
92                         if (val == null) {
93                                 ps.setString(index, null);
94                                 return;
95                         }
96                         StringBuilder sb = new StringBuilder();
97                         String sep = "";
98                         for (String s: val) {
99                                 sb.append(sep).append(fesc(s));
100                                 sep = ",";
101                         }
102                         ps.setString(index, sb.toString());
103                 }
104         }
105         private static class    EnumSql implements SqlOp {
106                 private Class   enclass;
107                 public EnumSql(Class enclass) {
108                         this.enclass = enclass;
109                 }
110                 @SuppressWarnings("unchecked")
111                 public Object get(ResultSet rs, int index) throws Exception {
112                         String val = rs.getString(index);
113                         if (val == null) {
114                                 return(null);
115                         } else {
116                                 return(Enum.valueOf(enclass, val));
117                         }
118                 }
119                 public void set(PreparedStatement ps, int index, Object value) throws Exception {
120                         if (value == null) {
121                                 ps.setString(index, null);
122                         } else {
123                                 ps.setString(index, value.toString());
124                         }
125                 }
126         }
127         private static class    SqlDate implements SqlOp {
128                 public Object get(ResultSet rs, int index) throws Exception {
129                         return(rs.getTimestamp(index));
130                 }
131                 public void set(PreparedStatement ps, int index, Object val) throws Exception {
132                         if (val instanceof java.util.Date && !(val instanceof java.sql.Timestamp)) {
133                                 val = new java.sql.Timestamp(((java.util.Date)val).getTime());
134                         }
135                         ps.setTimestamp(index, (java.sql.Timestamp)val);
136                 }
137         }
138         private static class    SqlType implements SqlOp {
139                 private Method   sqlget;
140                 private Method   sqlset;
141                 private SqlType(String tag) throws Exception {
142                         sqlget = ResultSet.class.getMethod("get" + tag, Integer.TYPE);
143                         sqlset = PreparedStatement.class.getMethod("set" + tag, Integer.TYPE, sqlget.getReturnType());
144                         sqltypes.put(sqlget.getReturnType().getName(), this);
145                 }
146                 public Object get(ResultSet rs, int index) throws Exception {
147                         return(sqlget.invoke(rs, index));
148                 }
149                 public void set(PreparedStatement ps, int index, Object val) throws Exception {
150                         try {
151                                 sqlset.invoke(ps, index, val);
152                         } catch (Exception e) {
153                                 errorLogger.error(DmaapbcLogMessageEnum.DB_FIELD_INIT_ERROR,  Integer.toString(index), val.toString(), ps.toString());
154                                 throw e;
155                         }
156                 }
157         }
158         private static Map<String, SqlOp> sqltypes;
159         static {
160                 sqltypes = new HashMap<>();
161                 sqltypes.put("[Ljava.lang.String;", new AofString());
162                 sqltypes.put("java.util.Date", new SqlDate());
163                 try {
164                         new SqlType("Boolean");
165                         new SqlType("Timestamp");
166                         new SqlType("Double");
167                         new SqlType("Float");
168                         new SqlType("Int");
169                         new SqlType("Long");
170                         new SqlType("Short");
171                         new SqlType("String");
172                 } catch (Exception e) {
173                         errorLogger.error("Error", e);
174                         errorLogger.error(DmaapbcLogMessageEnum.DB_ACCESS_INIT_ERROR,  e.getMessage() );
175                 }
176         }
177         private Method  objget;
178         private Method  objset;
179         private SqlOp   sqlop;
180         private int     fieldnum;
181         public void copy(Object from, Object to) throws Exception {
182                 objset.invoke(to, objget.invoke(from));
183         }
184         public void setKey(Object o, String key) throws Exception {
185                 objset.invoke(o, key);
186         }
187         public String getKey(Object o) throws Exception {
188                 return((String)objget.invoke(o));
189         }
190         public void toSQL(Object o, PreparedStatement ps) throws Exception {
191                 sqlop.set(ps, fieldnum, objget.invoke(o));
192         }
193         public void fromSQL(ResultSet r, Object o) throws Exception {
194                 objset.invoke(o, sqlop.get(r, fieldnum));
195         }
196         public static String fesc(String s) {
197                 if (s == null) {
198                         return(s);
199                 }
200                 return(s.replaceAll("@", "@a").replaceAll(";", "@s").replaceAll(",", "@c"));
201         }
202         public static String funesc(String s) {
203                 if (s == null) {
204                         return(s);
205                 }
206                 return(s.replaceAll("@c", ",").replaceAll("@s", ";").replaceAll("@a", "@"));
207         }
208 }