Remove major and minor code smells in dr-prov
[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             if ("success".equals(s)) {\r
317                 sql = " AND STATUS >= 200 AND STATUS < 300";\r
318             } else if ("redirect".equals(s)) {\r
319                 sql = " AND STATUS >= 300 AND STATUS < 400";\r
320             } else if ("failure".equals(s)) {\r
321                 sql = " AND STATUS >= 400";\r
322             } else {\r
323                 try {\r
324                     Integer n = Integer.parseInt(s);\r
325                     if ((n >= 100 && n < 600) || (n == -1))\r
326                         sql = " AND STATUS = " + n;\r
327                 } catch (NumberFormatException e) {\r
328                 }\r
329             }\r
330             if (sql == null) {\r
331                 map.put("err", "bad statusCode");\r
332                 return map;\r
333             }\r
334             map.put(STATUSSQL, sql);\r
335             map.put(RESULTSQL, sql.replaceAll("STATUS", "RESULT"));\r
336         }\r
337 \r
338         s = req.getParameter("expiryReason");\r
339         if (s != null) {\r
340             map.put("type", "exp");\r
341             if ("notRetryable".equals(s)) {\r
342                 map.put(REASON_SQL, " AND REASON = 'notRetryable'");\r
343             } else if ("retriesExhausted".equals(s)) {\r
344                 map.put(REASON_SQL, " AND REASON = 'retriesExhausted'");\r
345             } else if ("diskFull".equals(s)) {\r
346                 map.put(REASON_SQL, " AND REASON = 'diskFull'");\r
347             } else if ("other".equals(s)) {\r
348                 map.put(REASON_SQL, " AND REASON = 'other'");\r
349             } else {\r
350                 map.put("err", "bad expiryReason");\r
351                 return map;\r
352             }\r
353         }\r
354 \r
355         long stime = getTimeFromParam(req.getParameter("start"));\r
356         if (stime < 0) {\r
357             map.put("err", "bad start");\r
358             return map;\r
359         }\r
360         long etime = getTimeFromParam(req.getParameter("end"));\r
361         if (etime < 0) {\r
362             map.put("err", "bad end");\r
363             return map;\r
364         }\r
365         if (stime == 0 && etime == 0) {\r
366             etime = System.currentTimeMillis();\r
367             stime = etime - TWENTYFOUR_HOURS;\r
368         } else if (stime == 0) {\r
369             stime = etime - TWENTYFOUR_HOURS;\r
370         } else if (etime == 0) {\r
371             etime = stime + TWENTYFOUR_HOURS;\r
372         }\r
373         map.put(TIMESQL, String.format(" AND EVENT_TIME >= %d AND EVENT_TIME <= %d", stime, etime));\r
374         return map;\r
375     }\r
376     private long getTimeFromParam(final String s) {\r
377         if (s == null)\r
378             return 0;\r
379         try {\r
380             // First, look for an RFC 3339 date\r
381             String fmt = (s.indexOf('.') > 0) ? FMT_2 : FMT_1;\r
382             SimpleDateFormat sdf = new SimpleDateFormat(fmt);\r
383             Date d = sdf.parse(s);\r
384             return d.getTime();\r
385         } catch (ParseException parseException) {\r
386             intlogger.error("Exception in getting Time :- "+parseException.getMessage(),parseException);\r
387         }\r
388         try {\r
389             // Also allow a long (in ms); useful for testing\r
390             return Long.parseLong(s);\r
391         } catch (NumberFormatException numberFormatException) {\r
392             intlogger.error("Exception in getting Time :- "+numberFormatException.getMessage(),numberFormatException);\r
393         }\r
394         intlogger.info("Error parsing time="+s);\r
395         return -1;\r
396     }\r
397 \r
398     private void getPublishRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
399         String type = map.get("type");\r
400         if ("all".equals(type) || "pub".equals(type)) {\r
401             String sql = LOG_RECORDSSQL+feedid\r
402                 + " AND TYPE = 'pub'"\r
403                 + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(STATUSSQL) + map.get(FILENAMESQL);\r
404             getRecordsForSQL(sql, rh);\r
405         }\r
406     }\r
407     private void getDeliveryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
408         String type = map.get("type");\r
409         if ("all".equals(type) || "del".equals(type)) {\r
410             String sql = LOG_RECORDSSQL+feedid\r
411                 + " AND TYPE = 'del'"\r
412                 + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(RESULTSQL);\r
413             getRecordsForSQL(sql, rh);\r
414         }\r
415     }\r
416     private void getDeliveryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {\r
417         String type = map.get("type");\r
418         if ("all".equals(type) || "del".equals(type)) {\r
419             String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = "+subid\r
420                 + " AND TYPE = 'del'"\r
421                 + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(RESULTSQL);\r
422             getRecordsForSQL(sql, rh);\r
423         }\r
424     }\r
425     private void getExpiryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
426         String type = map.get("type");\r
427         if ("all".equals(type) || "exp".equals(type)) {\r
428             String st = map.get(STATUSSQL);\r
429             if (st == null || st.length() == 0) {\r
430                 String sql = LOG_RECORDSSQL+feedid\r
431                     + " AND TYPE = 'exp'"\r
432                     + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(REASON_SQL);\r
433                 getRecordsForSQL(sql, rh);\r
434             }\r
435         }\r
436     }\r
437     private void getExpiryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {\r
438         String type = map.get("type");\r
439         if ("all".equals(type) || "exp".equals(type)) {\r
440             String st = map.get(STATUSSQL);\r
441             if (st == null || st.length() == 0) {\r
442                 String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = "+subid\r
443                     + " AND TYPE = 'exp'"\r
444                     + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(REASON_SQL);\r
445                 getRecordsForSQL(sql, rh);\r
446             }\r
447         }\r
448     }\r
449     private void getRecordsForSQL(String sql, RowHandler rh) {\r
450         intlogger.debug(sql);\r
451         long start = System.currentTimeMillis();\r
452         DB db = new DB();\r
453         Connection conn = null;\r
454         try {\r
455             conn = db.getConnection();\r
456            try( Statement  stmt = conn.createStatement()){\r
457              try(ResultSet rs = stmt.executeQuery(sql)){\r
458                  while (rs.next()) {\r
459                      rh.handleRow(rs);\r
460                  }\r
461              }\r
462            }\r
463         } catch (SQLException sqlException) {\r
464             intlogger.info("Failed to get Records. Exception = " +sqlException.getMessage(),sqlException);\r
465         } finally {\r
466             if (conn != null)\r
467                 db.release(conn);\r
468         }\r
469         intlogger.debug("Time: " + (System.currentTimeMillis()-start) + " ms");\r
470     }\r
471 }\r