Refactor dblib
[ccsdk/sli/core.git] / sli / common / src / main / java / org / onap / ccsdk / sli / core / sli / MessageWriter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : CCSDK
4  * ================================================================================
5  * Copyright (C) 2017 ONAP
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.ccsdk.sli.core.sli;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.sql.SQLException;
26 import java.text.SimpleDateFormat;
27 import java.util.ArrayList;
28 import java.util.Date;
29 import java.util.Properties;
30
31 import javax.sql.rowset.CachedRowSet;
32
33 import org.onap.ccsdk.sli.core.dblib.DbLibService;
34 import org.osgi.framework.BundleContext;
35 import org.osgi.framework.FrameworkUtil;
36 import org.osgi.framework.ServiceReference;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40
41 public class MessageWriter {
42
43         private static final Logger LOG = LoggerFactory.getLogger(MessageWriter.class);
44
45         private static final String DBLIB_SERVICE = "org.onap.ccsdk.sli.core.dblib.DBResourceManager";
46         private static final String SVCLOGIC_PROP_VAR = "SDNC_SLI_PROPERTIES";
47         private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR";
48
49         private static final String INCOMING_PROPERTY_NAME = "org.onap.ccsdk.sli.MessageWriter.writeIncomingRequests";
50         private static final String OUTGOING_PROPERTY_NAME = "org.onap.ccsdk.sli.MessageWriter.writeOutgoingRequests";
51
52         private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
53
54         private static DbLibService dbLibService = null;
55
56         private static boolean incomingEnabled = false;
57         private static boolean outgoingEnabled = false;
58
59         private static boolean initialized = false;
60
61         @SuppressWarnings({ "rawtypes", "unchecked" })
62         private static void init() {
63                 if (initialized)
64                         return;
65
66                 initialized = true;
67
68                 // Read properties
69                 Properties props = new Properties();
70                 String propPath = System.getenv(SVCLOGIC_PROP_VAR);
71
72                 if (propPath == null) {
73                         String propDir = System.getenv(SDNC_CONFIG_DIR);
74                         if (propDir == null) {
75                                 propDir = "/opt/sdnc/data/properties";
76                         }
77                         propPath = propDir + "/svclogic.properties";
78                         LOG.warn("Environment variable " + SVCLOGIC_PROP_VAR + " unset - defaulting to " + propPath);
79                 }
80
81                 File propFile = new File(propPath);
82
83                 if (!propFile.exists()) {
84                         LOG.warn("Property file does not exist: " + propPath);
85                 }
86
87                 try {
88                         props.load(new FileInputStream(propFile));
89                 } catch (Exception e) {
90                         LOG.warn("Error loading property file: " + propPath, e);
91                 }
92
93                 incomingEnabled = Boolean.valueOf(props.getProperty(INCOMING_PROPERTY_NAME, "false"));
94                 outgoingEnabled = Boolean.valueOf(props.getProperty(OUTGOING_PROPERTY_NAME, "false"));
95
96                 LOG.info(INCOMING_PROPERTY_NAME + ": " + incomingEnabled);
97                 LOG.info(OUTGOING_PROPERTY_NAME + ": " + outgoingEnabled);
98
99                 if (dbLibService != null)
100                         return;
101
102                 BundleContext bctx = FrameworkUtil.getBundle(MessageWriter.class).getBundleContext();
103
104                 ServiceReference sref = bctx.getServiceReference(DBLIB_SERVICE);
105
106                 if (sref == null) {
107                         LOG.warn("Could not find service reference for DBLIB service (" + DBLIB_SERVICE + ")");
108                 } else {
109                         dbLibService = (DbLibService) bctx.getService(sref);
110                         if (dbLibService == null) {
111                                 LOG.warn("Could not find service reference for DBLIB service (" + DBLIB_SERVICE + ")");
112                         }
113                 }
114         }
115
116         public static void saveOutgoingRequest(
117                 String requestId,
118                 String serviceInstanceId,
119                 String targetUrl,
120                 String request) {
121                 try {
122                         init();
123
124                         if (!outgoingEnabled)
125                                 return;
126
127                         if (serviceInstanceId == null || serviceInstanceId.trim().length() == 0)
128                                 serviceInstanceId = "NA";
129
130                         int seqnum = getLastSequenceNumber("OUTGOING_MESSAGE", requestId) + 1;
131                         String now = df.format(new Date());
132
133                         String sql = "INSERT INTO OUTGOING_MESSAGE (\n" +
134                                 "       request_id, sequence_number, service_instance_id, target_url, request, start_time)\n" +
135                                 "VALUES (?, ?, ?, ?, ?, ?)";
136
137                         ArrayList<String> data = new ArrayList<>();
138                         data.add(requestId);
139                         data.add(String.valueOf(seqnum));
140                         data.add(serviceInstanceId);
141                         data.add(targetUrl);
142                         data.add(request);
143                         data.add(now);
144
145                         dbLibService.writeData(sql, data, null);
146
147                 } catch (Exception e) {
148                         LOG.warn("Failed to save outgoing request for request-id: " + requestId, e);
149                 }
150         }
151
152         public static void saveOutgoingResponse(String requestId, int httpResponseCode, String response) {
153                 try {
154                         init();
155
156                         if (!outgoingEnabled)
157                                 return;
158
159                         int seqnum = getLastSequenceNumber("OUTGOING_MESSAGE", requestId);
160                         if (seqnum == 0) {
161                                 LOG.warn("Failed to save outgoing response for request-id: " + requestId +
162                                         ": Request record not found in OUTGOING_MESSAGE");
163                                 return;
164                         }
165
166                         String now = df.format(new Date());
167
168                         String sql = "UPDATE OUTGOING_MESSAGE SET http_response_code = ?, response = ?,\n" +
169                                 "       duration = timestampdiff(MICROSECOND, start_time, ?) / 1000\n" +
170                                 "WHERE request_id = ? AND sequence_number = ?";
171
172                         ArrayList<String> data = new ArrayList<>();
173                         data.add(String.valueOf(httpResponseCode));
174                         data.add(response);
175                         data.add(now);
176                         data.add(requestId);
177                         data.add(String.valueOf(seqnum));
178
179                         dbLibService.writeData(sql, data, null);
180
181                 } catch (Exception e) {
182                         LOG.warn("Failed to save outgoing response for request-id: " + requestId, e);
183                 }
184         }
185
186         public static void saveIncomingRequest(
187                 String requestId,
188                 String serviceInstanceId,
189                 String requestHost,
190                 String request) {
191                 try {
192                         init();
193
194                         if (!incomingEnabled)
195                                 return;
196
197                         if (serviceInstanceId == null || serviceInstanceId.trim().length() == 0)
198                                 serviceInstanceId = "NA";
199
200                         int seqnum = getLastSequenceNumber("INCOMING_MESSAGE", requestId) + 1;
201                         String now = df.format(new Date());
202
203                         String sql = "INSERT INTO INCOMING_MESSAGE (\n" +
204                                 "       request_id, sequence_number, service_instance_id, request_host, request, start_time)\n" +
205                                 "VALUES (?, ?, ?, ?, ?, ?)";
206
207                         ArrayList<String> data = new ArrayList<>();
208                         data.add(requestId);
209                         data.add(String.valueOf(seqnum));
210                         data.add(serviceInstanceId);
211                         data.add(requestHost);
212                         data.add(request);
213                         data.add(now);
214
215                         dbLibService.writeData(sql, data, null);
216
217                 } catch (Exception e) {
218                         LOG.warn("Failed to save incoming request for request-id: " + requestId, e);
219                 }
220         }
221
222         public static void saveIncomingResponse(String requestId, int httpResponseCode, String response) {
223                 try {
224                         init();
225
226                         if (!incomingEnabled)
227                                 return;
228
229                         int seqnum = getLastSequenceNumber("INCOMING_MESSAGE", requestId);
230                         if (seqnum == 0) {
231                                 LOG.warn("Failed to save response for request-id: " + requestId +
232                                         ": Request record not found in INCOMING_MESSAGE");
233                                 return;
234                         }
235
236                         String now = df.format(new Date());
237
238                         String sql = "UPDATE INCOMING_MESSAGE SET http_response_code = ?, response = ?,\n" +
239                                 "       duration = timestampdiff(MICROSECOND, start_time, ?) / 1000\n" +
240                                 "WHERE request_id = ? AND sequence_number = ?";
241
242                         ArrayList<String> data = new ArrayList<>();
243                         data.add(String.valueOf(httpResponseCode));
244                         data.add(response);
245                         data.add(now);
246                         data.add(requestId);
247                         data.add(String.valueOf(seqnum));
248
249                         dbLibService.writeData(sql, data, null);
250
251                 } catch (Exception e) {
252                         LOG.warn("Failed to save response for request-id: " + requestId, e);
253                 }
254         }
255
256         public static String getServiceInstanceId(String requestId) throws SQLException {
257                 init();
258
259                 String sql = "SELECT service_instance_id FROM OUTGOING_MESSAGE WHERE request_id = '" + requestId +
260                         "' ORDER BY sequence_number DESC";
261
262                 CachedRowSet rs = null;
263                 try {
264                         rs = dbLibService.getData(sql, null, null);
265                         if (rs.next()) {
266                                 return rs.getString("service_instance_id");
267                         }
268                 } finally {
269                         if (rs != null) {
270                                 try {
271                                         rs.close();
272                                 } catch (Exception e) {
273                                         LOG.warn("Failed to close CachedRowSet", e);
274                                 }
275                         }
276                 }
277                 return null;
278         }
279
280         private static int getLastSequenceNumber(String tableName, String requestId) throws SQLException {
281                 String sql = "SELECT sequence_number FROM " + tableName + " WHERE request_id = '" + requestId +
282                         "' ORDER BY sequence_number DESC";
283
284                 CachedRowSet rs = null;
285                 try {
286                         rs = dbLibService.getData(sql, null, null);
287                         if (rs.next()) {
288                                 return rs.getInt("sequence_number");
289                         }
290                 } finally {
291                         if (rs != null) {
292                                 try {
293                                         rs.close();
294                                 } catch (Exception e) {
295                                         LOG.warn("Failed to close CachedRowSet", e);
296                                 }
297                         }
298                 }
299                 return 0;
300         }
301 }