52af453ca178faa76429eaa970d11f1678cf9182
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / aaf / 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  * 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.lang.reflect.*;
24 import java.sql.*;
25 import java.util.*;
26
27 import org.apache.log4j.Logger;
28
29 import com.att.eelf.configuration.EELFLogger;
30 import com.att.eelf.configuration.EELFManager;
31
32 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
33
34
35 public class DBFieldHandler     {
36         static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
37         
38         public static interface SqlOp   {
39                 public Object get(ResultSet rs, int index) throws Exception;
40                 public void set(PreparedStatement ps, int index, Object value) throws Exception;
41         }
42         private static class    AofString implements SqlOp {
43                 public Object get(ResultSet rs, int index) throws Exception {
44                         String val = rs.getString(index);
45                         if (val == null) {
46                                 return(null);
47                         }
48                         String[] ret = val.split(",");
49                         for (int i = 0; i < ret.length; i++) {
50                                 ret[i] = funesc(ret[i]);
51                         }
52                         return(ret);
53                 }
54                 public void set(PreparedStatement ps, int index, Object x) throws Exception {
55                         String[] val = (String[])x;
56                         if (val == null) {
57                                 ps.setString(index, null);
58                                 return;
59                         }
60                         StringBuffer sb = new StringBuffer();
61                         String sep = "";
62                         for (String s: val) {
63                                 sb.append(sep).append(fesc(s));
64                                 sep = ",";
65                         }
66                         ps.setString(index, sb.toString());
67                 }
68         }
69         private static class    EnumSql implements SqlOp {
70                 private Class   enclass;
71                 public EnumSql(Class enclass) {
72                         this.enclass = enclass;
73                 }
74                 @SuppressWarnings("unchecked")
75                 public Object get(ResultSet rs, int index) throws Exception {
76                         String val = rs.getString(index);
77                         if (val == null) {
78                                 return(null);
79                         } else {
80                                 return(Enum.valueOf(enclass, val));
81                         }
82                 }
83                 public void set(PreparedStatement ps, int index, Object value) throws Exception {
84                         if (value == null) {
85                                 ps.setString(index, null);
86                         } else {
87                                 ps.setString(index, value.toString());
88                         }
89                 }
90         }
91         private static class    SqlDate implements SqlOp {
92                 public Object get(ResultSet rs, int index) throws Exception {
93                         return(rs.getTimestamp(index));
94                 }
95                 public void set(PreparedStatement ps, int index, Object val) throws Exception {
96                         if (val instanceof java.util.Date && !(val instanceof java.sql.Timestamp)) {
97                                 val = new java.sql.Timestamp(((java.util.Date)val).getTime());
98                         }
99                         ps.setTimestamp(index, (java.sql.Timestamp)val);
100                 }
101         }
102         private static class    SqlType implements SqlOp {
103                 private Method   sqlget;
104                 private Method   sqlset;
105                 private SqlType(String tag) throws Exception {
106                         sqlget = ResultSet.class.getMethod("get" + tag, Integer.TYPE);
107                         sqlset = PreparedStatement.class.getMethod("set" + tag, Integer.TYPE, sqlget.getReturnType());
108                         sqltypes.put(sqlget.getReturnType().getName(), this);
109                 }
110                 public Object get(ResultSet rs, int index) throws Exception {
111                         return(sqlget.invoke(rs, index));
112                 }
113                 public void set(PreparedStatement ps, int index, Object val) throws Exception {
114                         try {
115                                 sqlset.invoke(ps, index, val);
116                         } catch (Exception e) {
117                                 errorLogger.error(DmaapbcLogMessageEnum.DB_FIELD_INIT_ERROR,  Integer.toString(index), val.toString(), ps.toString());
118                                 throw e;
119                         }
120                 }
121         }
122         private static Map<String, SqlOp> sqltypes;
123         static {
124                 sqltypes = new HashMap<String, SqlOp>();
125                 sqltypes.put("[Ljava.lang.String;", new AofString());
126                 sqltypes.put("java.util.Date", new SqlDate());
127                 try {
128                         new SqlType("Boolean");
129                         new SqlType("Timestamp");
130                         new SqlType("Double");
131                         new SqlType("Float");
132                         new SqlType("Int");
133                         new SqlType("Long");
134                         new SqlType("Short");
135                         new SqlType("String");
136                 } catch (Exception e) {
137                         errorLogger.error(DmaapbcLogMessageEnum.DB_ACCESS_INIT_ERROR,  e.getMessage() );
138                 }
139         }
140         private Method  objget;
141         private Method  objset;
142         private SqlOp   sqlop;
143         private int     fieldnum;
144         public void copy(Object from, Object to) throws Exception {
145                 objset.invoke(to, objget.invoke(from));
146         }
147         public void setKey(Object o, String key) throws Exception {
148                 objset.invoke(o, key);
149         }
150         public String getKey(Object o) throws Exception {
151                 return((String)objget.invoke(o));
152         }
153         public void toSQL(Object o, PreparedStatement ps) throws Exception {
154                 sqlop.set(ps, fieldnum, objget.invoke(o));
155         }
156         public void fromSQL(ResultSet r, Object o) throws Exception {
157                 objset.invoke(o, sqlop.get(r, fieldnum));
158         }
159         public DBFieldHandler(Class<?> c, String fieldname, int fieldnum) throws Exception {
160                 this(c, fieldname, fieldnum, null);
161         }
162         public DBFieldHandler(Class<?> c, String fieldname, int fieldnum, SqlOp op) throws Exception {
163                 this.fieldnum = fieldnum;
164                 StringBuffer sb = new StringBuffer();
165                 for (String s: fieldname.split("_")) {
166                         sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1));
167                 }
168                 String camelcase = sb.toString();
169                 try {
170                         objget = c.getMethod("is" + camelcase);
171                 } catch (Exception e) {
172                         objget = c.getMethod("get" + camelcase);
173                 }
174                 objset = c.getMethod("set" + camelcase, objget.getReturnType());
175                 sqlop = op;
176                 if (sqlop != null) {
177                         return;
178                 }
179                 Class<?> x = objget.getReturnType();
180                 if (x.isEnum()) {
181                         sqlop = new EnumSql(x);
182                         return;
183                 }
184                 sqlop = sqltypes.get(x.getName());
185                 if (sqlop != null) {
186                         return;
187                 }
188                 errorLogger.error(DmaapbcLogMessageEnum.DB_NO_FIELD_HANDLER,  c.getName(),  fieldname,  Integer.toString(fieldnum),  x.getName());
189         }
190         public static String fesc(String s) {
191                 if (s == null) {
192                         return(s);
193                 }
194                 return(s.replaceAll("@", "@a").replaceAll(";", "@s").replaceAll(",", "@c"));
195         }
196         public static String funesc(String s) {
197                 if (s == null) {
198                         return(s);
199                 }
200                 return(s.replaceAll("@c", ",").replaceAll("@s", ";").replaceAll("@a", "@"));
201         }
202 }