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