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