Removing code smells
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / LogServlet.java
1 /*******************************************************************************\r
2  * ============LICENSE_START==================================================\r
3  * * org.onap.dmaap\r
4  * * ===========================================================================\r
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * * ===========================================================================\r
7  * * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * * you may not use this file except in compliance with the License.\r
9  * * You may obtain a copy of the License at\r
10  * *\r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * *\r
13  *  * Unless required by applicable law or agreed to in writing, software\r
14  * * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * * See the License for the specific language governing permissions and\r
17  * * limitations under the License.\r
18  * * ============LICENSE_END====================================================\r
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 \r
24 \r
25 package org.onap.dmaap.datarouter.provisioning;\r
26 \r
27 import java.io.IOException;\r
28 import java.sql.Connection;\r
29 import java.sql.ResultSet;\r
30 import java.sql.SQLException;\r
31 import java.sql.Statement;\r
32 import java.text.ParseException;\r
33 import java.text.SimpleDateFormat;\r
34 import java.util.Date;\r
35 import java.util.HashMap;\r
36 import java.util.Map;\r
37 \r
38 import javax.servlet.ServletOutputStream;\r
39 import javax.servlet.http.HttpServletRequest;\r
40 import javax.servlet.http.HttpServletResponse;\r
41 \r
42 import org.onap.dmaap.datarouter.provisioning.beans.DeliveryRecord;\r
43 import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;\r
44 import org.onap.dmaap.datarouter.provisioning.beans.ExpiryRecord;\r
45 import org.onap.dmaap.datarouter.provisioning.beans.LOGJSONable;\r
46 import org.onap.dmaap.datarouter.provisioning.beans.PublishRecord;\r
47 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;\r
48 import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;\r
49 import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
50 import org.onap.dmaap.datarouter.provisioning.utils.LOGJSONObject;\r
51 \r
52 import com.att.eelf.configuration.EELFLogger;\r
53 import com.att.eelf.configuration.EELFManager;\r
54 \r
55 import static org.onap.dmaap.datarouter.provisioning.utils.HttpServletUtils.sendResponseError;\r
56 \r
57 /**\r
58  * This servlet handles requests to the <feedLogURL> and  <subLogURL>,\r
59  * which are generated by the provisioning server to handle the log query API.\r
60  *\r
61  * @author Robert Eby\r
62  * @version $Id: LogServlet.java,v 1.11 2014/03/28 17:27:02 eby Exp $\r
63  */\r
64 @SuppressWarnings("serial")\r
65 public class LogServlet extends BaseServlet {\r
66     //Adding EELF Logger Rally:US664892\r
67     private static EELFLogger eelfLogger = EELFManager.getInstance().getLogger(LogServlet.class);\r
68     private static final long TWENTYFOUR_HOURS = (24 * 60 * 60 * 1000L);\r
69     private static final String FMT_1 = "yyyy-MM-dd'T'HH:mm:ss'Z'";\r
70     private static final String FMT_2 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";\r
71     private static final String PUBLISHSQL = "publishSQL";\r
72     private static final String STATUSSQL = "statusSQL";\r
73     private static final String RESULTSQL = "resultSQL";\r
74     private static final String FILENAMESQL = "filenameSQL";\r
75     private static final String TIMESQL = "timeSQL";\r
76     private static final String LOG_RECORDSSQL = "select * from LOG_RECORDS where FEEDID = ";\r
77 \r
78     private final boolean isfeedlog;\r
79 \r
80     public abstract class RowHandler {\r
81         private final ServletOutputStream out;\r
82         private final String[] fields;\r
83         private boolean firstrow;\r
84 \r
85         public RowHandler(ServletOutputStream out, String fieldparam, boolean b) {\r
86             this.out = out;\r
87             this.firstrow = b;\r
88             this.fields = (fieldparam != null) ? fieldparam.split(":") : null;\r
89         }\r
90         public void handleRow(ResultSet rs) {\r
91             try {\r
92                 LOGJSONable js = buildJSONable(rs);\r
93                 LOGJSONObject jo = js.asJSONObject();\r
94                 if (fields != null) {\r
95                     // filter out unwanted fields\r
96                     LOGJSONObject j2 = new LOGJSONObject();\r
97                     for (String key : fields) {\r
98                         Object v = jo.opt(key);\r
99                         if (v != null)\r
100                             j2.put(key, v);\r
101                     }\r
102                     jo = j2;\r
103                 }\r
104                 String t = firstrow ? "\n" : ",\n";\r
105                 t += jo.toString();\r
106                 out.print(t);\r
107                 firstrow = false;\r
108             } catch (Exception exception) {\r
109                 intlogger.info("Failed to handle row. Exception = " + exception.getMessage(),exception);\r
110             }\r
111         }\r
112         public abstract LOGJSONable buildJSONable(ResultSet rs) throws SQLException;\r
113     }\r
114     public class PublishRecordRowHandler extends RowHandler {\r
115         public PublishRecordRowHandler(ServletOutputStream out, String fields, boolean b) {\r
116             super(out, fields, b);\r
117         }\r
118         @Override\r
119         public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {\r
120             return new PublishRecord(rs);\r
121         }\r
122     }\r
123     public class DeliveryRecordRowHandler extends RowHandler {\r
124         public DeliveryRecordRowHandler(ServletOutputStream out, String fields, boolean b) {\r
125             super(out, fields, b);\r
126         }\r
127         @Override\r
128         public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {\r
129             return new DeliveryRecord(rs);\r
130         }\r
131     }\r
132     public class ExpiryRecordRowHandler extends RowHandler {\r
133         public ExpiryRecordRowHandler(ServletOutputStream out, String fields, boolean b) {\r
134             super(out, fields, b);\r
135         }\r
136         @Override\r
137         public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {\r
138             return new ExpiryRecord(rs);\r
139         }\r
140     }\r
141 \r
142     /**\r
143      * This class must be created from either a {@link FeedLogServlet} or a {@link SubLogServlet}.\r
144      * @param isFeedLog boolean to handle those places where a feedlog request is different from\r
145      * a sublog request\r
146      */\r
147     protected LogServlet(boolean isFeedLog) {\r
148         this.isfeedlog = isFeedLog;\r
149     }\r
150 \r
151     /**\r
152      * DELETE a logging URL -- not supported.\r
153      */\r
154     @Override\r
155     public void doDelete(HttpServletRequest req, HttpServletResponse resp) {\r
156         setIpFqdnRequestIDandInvocationIDForEelf("doDelete", req);\r
157         eelfLogger.info(EelfMsgs.ENTRY);\r
158         try {\r
159             eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
160             String message = "DELETE not allowed for the logURL.";\r
161             EventLogRecord elr = new EventLogRecord(req);\r
162             elr.setMessage(message);\r
163             elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
164             eventlogger.error(elr.toString());\r
165             sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
166         } finally {\r
167             eelfLogger.info(EelfMsgs.EXIT);\r
168         }\r
169     }\r
170     /**\r
171      * GET a logging URL -- retrieve logging data for a feed or subscription.\r
172      * See the <b>Logging API</b> document for details on how this method should be invoked.\r
173      */\r
174     @Override\r
175     public void doGet(HttpServletRequest req, HttpServletResponse resp) {\r
176         setIpFqdnRequestIDandInvocationIDForEelf("doGet", req);\r
177         eelfLogger.info(EelfMsgs.ENTRY);\r
178         try {\r
179             eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
180             int id = getIdFromPath(req);\r
181             if (id < 0) {\r
182                 sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST, "Missing or bad feed/subscription number.", eventlogger);\r
183                 return;\r
184             }\r
185             Map<String, String> map = buildMapFromRequest(req);\r
186             if (map.get("err") != null) {\r
187                 sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST, "Invalid arguments: " + map.get("err"), eventlogger);\r
188                 return;\r
189             }\r
190             // check Accept: header??\r
191 \r
192             resp.setStatus(HttpServletResponse.SC_OK);\r
193             resp.setContentType(LOGLIST_CONTENT_TYPE);\r
194 \r
195             try (ServletOutputStream out = resp.getOutputStream()) {\r
196                 final String fields = req.getParameter("fields");\r
197 \r
198                 out.print("[");\r
199                 if (isfeedlog) {\r
200                     // Handle /feedlog/feedid request\r
201                     boolean firstrow = true;\r
202 \r
203                     // 1. Collect publish records for this feed\r
204                     RowHandler rh = new PublishRecordRowHandler(out, fields, firstrow);\r
205                     getPublishRecordsForFeed(id, rh, map);\r
206                     firstrow = rh.firstrow;\r
207 \r
208                     // 2. Collect delivery records for subscriptions to this feed\r
209                     rh = new DeliveryRecordRowHandler(out, fields, firstrow);\r
210                     getDeliveryRecordsForFeed(id, rh, map);\r
211                     firstrow = rh.firstrow;\r
212 \r
213                     // 3. Collect expiry records for subscriptions to this feed\r
214                     rh = new ExpiryRecordRowHandler(out, fields, firstrow);\r
215                     getExpiryRecordsForFeed(id, rh, map);\r
216                 } else {\r
217                     // Handle /sublog/subid request\r
218                     Subscription sub = Subscription.getSubscriptionById(id);\r
219                     if (sub != null) {\r
220                         // 1. Collect publish records for the feed this subscription feeds\r
221                         RowHandler rh = new PublishRecordRowHandler(out, fields, true);\r
222                         getPublishRecordsForFeed(sub.getFeedid(), rh, map);\r
223 \r
224                         // 2. Collect delivery records for this subscription\r
225                         rh = new DeliveryRecordRowHandler(out, fields, rh.firstrow);\r
226                         getDeliveryRecordsForSubscription(id, rh, map);\r
227 \r
228                         // 3. Collect expiry records for this subscription\r
229                         rh = new ExpiryRecordRowHandler(out, fields, rh.firstrow);\r
230                         getExpiryRecordsForSubscription(id, rh, map);\r
231                     }\r
232                 }\r
233                 out.print("]");\r
234             } catch (IOException ioe) {\r
235                 eventlogger.error("PROV0141 LogServlet.doGet: " + ioe.getMessage(), ioe);\r
236             }\r
237         } finally {\r
238             eelfLogger.info(EelfMsgs.EXIT);\r
239         }\r
240     }\r
241     /**\r
242      * PUT a logging URL -- not supported.\r
243      */\r
244     @Override\r
245     public void doPut(HttpServletRequest req, HttpServletResponse resp) {\r
246         setIpFqdnRequestIDandInvocationIDForEelf("doPut", req);\r
247         eelfLogger.info(EelfMsgs.ENTRY);\r
248         try {\r
249             eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");\r
250             String message = "PUT not allowed for the logURL.";\r
251             EventLogRecord elr = new EventLogRecord(req);\r
252             elr.setMessage(message);\r
253             elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
254             eventlogger.error(elr.toString());\r
255             sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
256         } finally {\r
257             eelfLogger.info(EelfMsgs.EXIT);\r
258         }\r
259     }\r
260     /**\r
261      * POST a logging URL -- not supported.\r
262      */\r
263     @Override\r
264     public void doPost(HttpServletRequest req, HttpServletResponse resp) {\r
265         setIpFqdnRequestIDandInvocationIDForEelf("doPost", req);\r
266         eelfLogger.info(EelfMsgs.ENTRY);\r
267         try {\r
268             eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));\r
269             String message = "POST not allowed for the logURL.";\r
270             EventLogRecord elr = new EventLogRecord(req);\r
271             elr.setMessage(message);\r
272             elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
273             eventlogger.error(elr.toString());\r
274             sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
275         } finally {\r
276             eelfLogger.info(EelfMsgs.EXIT);\r
277         }\r
278     }\r
279 \r
280     private Map<String, String> buildMapFromRequest(HttpServletRequest req) {\r
281         Map<String, String> map = new HashMap<>();\r
282         String s = req.getParameter("type");\r
283         if (s != null) {\r
284             if ("pub".equals(s) || "del".equals(s) || "exp".equals(s)) {\r
285                 map.put("type", s);\r
286             } else {\r
287                 map.put("err", "bad type");\r
288                 return map;\r
289             }\r
290         } else {\r
291             map.put("type", "all");\r
292         }\r
293         map.put(PUBLISHSQL, "");\r
294         map.put(STATUSSQL, "");\r
295         map.put(RESULTSQL, "");\r
296         map.put(REASON_SQL, "");\r
297         map.put(FILENAMESQL, "");\r
298 \r
299         s = req.getParameter("publishId");\r
300         if (s != null) {\r
301             if (s.indexOf("'") >= 0) {\r
302                 map.put("err", "bad publishId");\r
303                 return map;\r
304             }\r
305             map.put(PUBLISHSQL, " AND PUBLISH_ID = '"+s+"'");\r
306         }\r
307 \r
308         s = req.getParameter("filename");\r
309         if (s != null) {\r
310             map.put(FILENAMESQL, " AND FILENAME = '" + s + "'");\r
311         }\r
312 \r
313         s = req.getParameter("statusCode");\r
314         if (s != null) {\r
315             String sql = null;\r
316             switch (s) {\r
317                 case "success":\r
318                     sql = " AND STATUS >= 200 AND STATUS < 300";\r
319                     break;\r
320                 case "redirect":\r
321                     sql = " AND STATUS >= 300 AND STATUS < 400";\r
322                     break;\r
323                 case "failure":\r
324                     sql = " AND STATUS >= 400";\r
325                     break;\r
326                 default:\r
327                     try {\r
328                         int n = Integer.parseInt(s);\r
329                         if ((n >= 100 && n < 600) || (n == -1)) {\r
330                             sql = " AND STATUS = " + n;\r
331                         }\r
332                     } catch (NumberFormatException e) {\r
333                         intlogger.error("Failed to parse input", e);\r
334                     }\r
335                     break;\r
336             }\r
337             if (sql == null) {\r
338                 map.put("err", "bad statusCode");\r
339                 return map;\r
340             }\r
341             map.put(STATUSSQL, sql);\r
342             map.put(RESULTSQL, sql.replaceAll("STATUS", "RESULT"));\r
343         }\r
344 \r
345         s = req.getParameter("expiryReason");\r
346         if (s != null) {\r
347             map.put("type", "exp");\r
348             if ("notRetryable".equals(s)) {\r
349                 map.put(REASON_SQL, " AND REASON = 'notRetryable'");\r
350             } else if ("retriesExhausted".equals(s)) {\r
351                 map.put(REASON_SQL, " AND REASON = 'retriesExhausted'");\r
352             } else if ("diskFull".equals(s)) {\r
353                 map.put(REASON_SQL, " AND REASON = 'diskFull'");\r
354             } else if ("other".equals(s)) {\r
355                 map.put(REASON_SQL, " AND REASON = 'other'");\r
356             } else {\r
357                 map.put("err", "bad expiryReason");\r
358                 return map;\r
359             }\r
360         }\r
361 \r
362         long stime = getTimeFromParam(req.getParameter("start"));\r
363         if (stime < 0) {\r
364             map.put("err", "bad start");\r
365             return map;\r
366         }\r
367         long etime = getTimeFromParam(req.getParameter("end"));\r
368         if (etime < 0) {\r
369             map.put("err", "bad end");\r
370             return map;\r
371         }\r
372         if (stime == 0 && etime == 0) {\r
373             etime = System.currentTimeMillis();\r
374             stime = etime - TWENTYFOUR_HOURS;\r
375         } else if (stime == 0) {\r
376             stime = etime - TWENTYFOUR_HOURS;\r
377         } else if (etime == 0) {\r
378             etime = stime + TWENTYFOUR_HOURS;\r
379         }\r
380         map.put(TIMESQL, String.format(" AND EVENT_TIME >= %d AND EVENT_TIME <= %d", stime, etime));\r
381         return map;\r
382     }\r
383     private long getTimeFromParam(final String s) {\r
384         if (s == null)\r
385             return 0;\r
386         try {\r
387             // First, look for an RFC 3339 date\r
388             String fmt = (s.indexOf('.') > 0) ? FMT_2 : FMT_1;\r
389             SimpleDateFormat sdf = new SimpleDateFormat(fmt);\r
390             Date d = sdf.parse(s);\r
391             return d.getTime();\r
392         } catch (ParseException parseException) {\r
393             intlogger.error("Exception in getting Time :- " + parseException.getMessage(),parseException);\r
394         }\r
395         try {\r
396             // Also allow a long (in ms); useful for testing\r
397             return Long.parseLong(s);\r
398         } catch (NumberFormatException numberFormatException) {\r
399             intlogger.error("Exception in getting Time :- " + numberFormatException.getMessage(),numberFormatException);\r
400         }\r
401         intlogger.info("Error parsing time=" + s);\r
402         return -1;\r
403     }\r
404 \r
405     private void getPublishRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
406         String type = map.get("type");\r
407         if ("all".equals(type) || "pub".equals(type)) {\r
408             String sql = LOG_RECORDSSQL + feedid\r
409                 + " AND TYPE = 'pub'"\r
410                 + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(STATUSSQL) + map.get(FILENAMESQL);\r
411             getRecordsForSQL(sql, rh);\r
412         }\r
413     }\r
414     private void getDeliveryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
415         String type = map.get("type");\r
416         if ("all".equals(type) || "del".equals(type)) {\r
417             String sql = LOG_RECORDSSQL + feedid\r
418                 + " AND TYPE = 'del'"\r
419                 + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(RESULTSQL);\r
420             getRecordsForSQL(sql, rh);\r
421         }\r
422     }\r
423     private void getDeliveryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {\r
424         String type = map.get("type");\r
425         if ("all".equals(type) || "del".equals(type)) {\r
426             String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = " + subid\r
427                 + " AND TYPE = 'del'"\r
428                 + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(RESULTSQL);\r
429             getRecordsForSQL(sql, rh);\r
430         }\r
431     }\r
432     private void getExpiryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
433         String type = map.get("type");\r
434         if ("all".equals(type) || "exp".equals(type)) {\r
435             String st = map.get(STATUSSQL);\r
436             if (st == null || st.length() == 0) {\r
437                 String sql = LOG_RECORDSSQL + feedid\r
438                     + " AND TYPE = 'exp'"\r
439                     + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(REASON_SQL);\r
440                 getRecordsForSQL(sql, rh);\r
441             }\r
442         }\r
443     }\r
444     private void getExpiryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {\r
445         String type = map.get("type");\r
446         if ("all".equals(type) || "exp".equals(type)) {\r
447             String st = map.get(STATUSSQL);\r
448             if (st == null || st.length() == 0) {\r
449                 String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = " + subid\r
450                     + " AND TYPE = 'exp'"\r
451                     + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(REASON_SQL);\r
452                 getRecordsForSQL(sql, rh);\r
453             }\r
454         }\r
455     }\r
456 \r
457     private void getRecordsForSQL(String sql, RowHandler rh) {\r
458         intlogger.debug(sql);\r
459         long start = System.currentTimeMillis();\r
460         DB db = new DB();\r
461         Connection conn = null;\r
462         try {\r
463             conn = db.getConnection();\r
464             try (Statement  stmt = conn.createStatement()) {\r
465                 try (ResultSet rs = stmt.executeQuery(sql)) {\r
466                     while (rs.next()) {\r
467                         rh.handleRow(rs);\r
468                     }\r
469                 }\r
470             }\r
471         } catch (SQLException sqlException) {\r
472             intlogger.info("Failed to get Records. Exception = " + sqlException.getMessage(),sqlException);\r
473         } finally {\r
474             if (conn != null)\r
475                 db.release(conn);\r
476         }\r
477         intlogger.debug("Time: " + (System.currentTimeMillis() - start) + " ms");\r
478     }\r
479 }\r