Remove major and minor code smells in dr-prov
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / LogServlet.java
index 48a2392..762ab4e 100644 (file)
@@ -52,6 +52,8 @@ import org.onap.dmaap.datarouter.provisioning.utils.LOGJSONObject;
 import com.att.eelf.configuration.EELFLogger;\r
 import com.att.eelf.configuration.EELFManager;\r
 \r
+import static org.onap.dmaap.datarouter.provisioning.utils.HttpServletUtils.sendResponseError;\r
+\r
 /**\r
  * This servlet handles requests to the <feedLogURL> and  <subLogURL>,\r
  * which are generated by the provisioning server to handle the log query API.\r
@@ -62,18 +64,23 @@ import com.att.eelf.configuration.EELFManager;
 @SuppressWarnings("serial")\r
 public class LogServlet extends BaseServlet {\r
     //Adding EELF Logger Rally:US664892\r
-    private static EELFLogger eelflogger = EELFManager.getInstance().getLogger("org.onap.dmaap.datarouter.provisioning.LogServlet");\r
-\r
+    private static EELFLogger eelfLogger = EELFManager.getInstance().getLogger(LogServlet.class);\r
     private static final long TWENTYFOUR_HOURS = (24 * 60 * 60 * 1000L);\r
-    private static final String fmt1 = "yyyy-MM-dd'T'HH:mm:ss'Z'";\r
-    private static final String fmt2 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";\r
+    private static final String FMT_1 = "yyyy-MM-dd'T'HH:mm:ss'Z'";\r
+    private static final String FMT_2 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";\r
+    private static final String PUBLISHSQL = "publishSQL";\r
+    private static final String STATUSSQL = "statusSQL";\r
+    private static final String RESULTSQL = "resultSQL";\r
+    private static final String FILENAMESQL = "filenameSQL";\r
+    private static final String TIMESQL = "timeSQL";\r
+    private static final String LOG_RECORDSSQL = "select * from LOG_RECORDS where FEEDID = ";\r
 \r
-    private boolean isfeedlog;\r
+    private final boolean isfeedlog;\r
 \r
     public abstract class RowHandler {\r
         private final ServletOutputStream out;\r
         private final String[] fields;\r
-        public boolean firstrow;\r
+        private boolean firstrow;\r
 \r
         public RowHandler(ServletOutputStream out, String fieldparam, boolean b) {\r
             this.out = out;\r
@@ -98,8 +105,8 @@ public class LogServlet extends BaseServlet {
                 t += jo.toString();\r
                 out.print(t);\r
                 firstrow = false;\r
-            } catch (Exception e) {\r
-                // ignore\r
+            } catch (Exception exception) {\r
+                intlogger.info("Failed to handle row. Exception = " + exception.getMessage(),exception);\r
             }\r
         }\r
         public abstract LOGJSONable buildJSONable(ResultSet rs) throws SQLException;\r
@@ -145,124 +152,149 @@ public class LogServlet extends BaseServlet {
      * DELETE a logging URL -- not supported.\r
      */\r
     @Override\r
-    public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {\r
-        setIpAndFqdnForEelf("doDelete");\r
-        eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");\r
-        String message = "DELETE not allowed for the logURL.";\r
-        EventLogRecord elr = new EventLogRecord(req);\r
-        elr.setMessage(message);\r
-        elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
-        eventlogger.info(elr);\r
-        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, message);\r
+    public void doDelete(HttpServletRequest req, HttpServletResponse resp) {\r
+        setIpFqdnRequestIDandInvocationIDForEelf("doDelete", req);\r
+        eelfLogger.info(EelfMsgs.ENTRY);\r
+        try {\r
+            eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
+            String message = "DELETE not allowed for the logURL.";\r
+            EventLogRecord elr = new EventLogRecord(req);\r
+            elr.setMessage(message);\r
+            elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
+            eventlogger.error(elr.toString());\r
+            sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
+        } finally {\r
+        eelfLogger.info(EelfMsgs.EXIT);\r
+    }\r
     }\r
     /**\r
      * GET a logging URL -- retrieve logging data for a feed or subscription.\r
      * See the <b>Logging API</b> document for details on how this method should be invoked.\r
      */\r
     @Override\r
-    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {\r
-        setIpAndFqdnForEelf("doGet");\r
-        eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");\r
-        int id = getIdFromPath(req);\r
-        if (id < 0) {\r
-            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing or bad feed/subscription number.");\r
-            return;\r
-        }\r
-        Map<String, String> map = buildMapFromRequest(req);\r
-        if (map.get("err") != null) {\r
-            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid arguments: "+map.get("err"));\r
-            return;\r
-        }\r
-        // check Accept: header??\r
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) {\r
+        setIpFqdnRequestIDandInvocationIDForEelf("doGet", req);\r
+        eelfLogger.info(EelfMsgs.ENTRY);\r
+        try {\r
+            eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");\r
+            int id = getIdFromPath(req);\r
+            if (id < 0) {\r
+                sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST, "Missing or bad feed/subscription number.", eventlogger);\r
+                return;\r
+            }\r
+            Map<String, String> map = buildMapFromRequest(req);\r
+            if (map.get("err") != null) {\r
+                sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST, "Invalid arguments: " + map.get("err"), eventlogger);\r
+                return;\r
+            }\r
+            // check Accept: header??\r
 \r
-        resp.setStatus(HttpServletResponse.SC_OK);\r
-        resp.setContentType(LOGLIST_CONTENT_TYPE);\r
-        @SuppressWarnings("resource")\r
-        ServletOutputStream out = resp.getOutputStream();\r
-        final String fields = req.getParameter("fields");\r
+            resp.setStatus(HttpServletResponse.SC_OK);\r
+            resp.setContentType(LOGLIST_CONTENT_TYPE);\r
 \r
-        out.print("[");\r
-        if (isfeedlog) {\r
-            // Handle /feedlog/feedid request\r
-            boolean firstrow = true;\r
+            try (ServletOutputStream out = resp.getOutputStream()) {\r
+                final String fields = req.getParameter("fields");\r
 \r
-            // 1. Collect publish records for this feed\r
-            RowHandler rh = new PublishRecordRowHandler(out, fields, firstrow);\r
-            getPublishRecordsForFeed(id, rh, map);\r
-            firstrow = rh.firstrow;\r
+                out.print("[");\r
+                if (isfeedlog) {\r
+                    // Handle /feedlog/feedid request\r
+                    boolean firstrow = true;\r
 \r
-            // 2. Collect delivery records for subscriptions to this feed\r
-            rh = new DeliveryRecordRowHandler(out, fields, firstrow);\r
-            getDeliveryRecordsForFeed(id, rh, map);\r
-            firstrow = rh.firstrow;\r
+                    // 1. Collect publish records for this feed\r
+                    RowHandler rh = new PublishRecordRowHandler(out, fields, firstrow);\r
+                    getPublishRecordsForFeed(id, rh, map);\r
+                    firstrow = rh.firstrow;\r
 \r
-            // 3. Collect expiry records for subscriptions to this feed\r
-            rh = new ExpiryRecordRowHandler(out, fields, firstrow);\r
-            getExpiryRecordsForFeed(id, rh, map);\r
-        } else {\r
-            // Handle /sublog/subid request\r
-            Subscription sub = Subscription.getSubscriptionById(id);\r
-            if (sub != null) {\r
-                // 1. Collect publish records for the feed this subscription feeds\r
-                RowHandler rh = new PublishRecordRowHandler(out, fields, true);\r
-                getPublishRecordsForFeed(sub.getFeedid(), rh, map);\r
+                    // 2. Collect delivery records for subscriptions to this feed\r
+                    rh = new DeliveryRecordRowHandler(out, fields, firstrow);\r
+                    getDeliveryRecordsForFeed(id, rh, map);\r
+                    firstrow = rh.firstrow;\r
+\r
+                    // 3. Collect expiry records for subscriptions to this feed\r
+                    rh = new ExpiryRecordRowHandler(out, fields, firstrow);\r
+                    getExpiryRecordsForFeed(id, rh, map);\r
+                } else {\r
+                    // Handle /sublog/subid request\r
+                    Subscription sub = Subscription.getSubscriptionById(id);\r
+                    if (sub != null) {\r
+                        // 1. Collect publish records for the feed this subscription feeds\r
+                        RowHandler rh = new PublishRecordRowHandler(out, fields, true);\r
+                        getPublishRecordsForFeed(sub.getFeedid(), rh, map);\r
 \r
-                // 2. Collect delivery records for this subscription\r
-                rh = new DeliveryRecordRowHandler(out, fields, rh.firstrow);\r
-                getDeliveryRecordsForSubscription(id, rh, map);\r
+                        // 2. Collect delivery records for this subscription\r
+                        rh = new DeliveryRecordRowHandler(out, fields, rh.firstrow);\r
+                        getDeliveryRecordsForSubscription(id, rh, map);\r
 \r
-                // 3. Collect expiry records for this subscription\r
-                rh = new ExpiryRecordRowHandler(out, fields, rh.firstrow);\r
-                getExpiryRecordsForSubscription(id, rh, map);\r
+                        // 3. Collect expiry records for this subscription\r
+                        rh = new ExpiryRecordRowHandler(out, fields, rh.firstrow);\r
+                        getExpiryRecordsForSubscription(id, rh, map);\r
+                    }\r
+                }\r
+                out.print("]");\r
+            } catch (IOException ioe) {\r
+                eventlogger.error("PROV0141 LogServlet.doGet: " + ioe.getMessage(), ioe);\r
             }\r
+        } finally {\r
+            eelfLogger.info(EelfMsgs.EXIT);\r
         }\r
-        out.print("\n]");\r
     }\r
     /**\r
      * PUT a logging URL -- not supported.\r
      */\r
     @Override\r
-    public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {\r
-        setIpAndFqdnForEelf("doPut");\r
-        eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");\r
+    public void doPut(HttpServletRequest req, HttpServletResponse resp) {\r
+        setIpFqdnRequestIDandInvocationIDForEelf("doPut", req);\r
+        eelfLogger.info(EelfMsgs.ENTRY);\r
+        try {\r
+        eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");\r
         String message = "PUT not allowed for the logURL.";\r
         EventLogRecord elr = new EventLogRecord(req);\r
         elr.setMessage(message);\r
         elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
-        eventlogger.info(elr);\r
-        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, message);\r
+        eventlogger.error(elr.toString());\r
+        sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
+        } finally {\r
+            eelfLogger.info(EelfMsgs.EXIT);\r
+        }\r
     }\r
     /**\r
      * POST a logging URL -- not supported.\r
      */\r
     @Override\r
-    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {\r
-        setIpAndFqdnForEelf("doPost");\r
-        eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));\r
+    public void doPost(HttpServletRequest req, HttpServletResponse resp) {\r
+        setIpFqdnRequestIDandInvocationIDForEelf("doPost", req);\r
+        eelfLogger.info(EelfMsgs.ENTRY);\r
+        try {\r
+        eelfLogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));\r
         String message = "POST not allowed for the logURL.";\r
         EventLogRecord elr = new EventLogRecord(req);\r
         elr.setMessage(message);\r
         elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
-        eventlogger.info(elr);\r
-        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, message);\r
+        eventlogger.error(elr.toString());\r
+        sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
+        } finally {\r
+            eelfLogger.info(EelfMsgs.EXIT);\r
+        }\r
     }\r
 \r
     private Map<String, String> buildMapFromRequest(HttpServletRequest req) {\r
-        Map<String, String> map = new HashMap<String, String>();\r
+        Map<String, String> map = new HashMap<>();\r
         String s = req.getParameter("type");\r
         if (s != null) {\r
-            if (s.equals("pub") || s.equals("del") || s.equals("exp")) {\r
+            if ("pub".equals(s) || "del".equals(s) || "exp".equals(s)) {\r
                 map.put("type", s);\r
             } else {\r
                 map.put("err", "bad type");\r
                 return map;\r
             }\r
-        } else\r
+        } else {\r
             map.put("type", "all");\r
-        map.put("publishSQL", "");\r
-        map.put("statusSQL", "");\r
-        map.put("resultSQL", "");\r
-        map.put("reasonSQL", "");\r
+        }\r
+        map.put(PUBLISHSQL, "");\r
+        map.put(STATUSSQL, "");\r
+        map.put(RESULTSQL, "");\r
+        map.put(REASON_SQL, "");\r
+        map.put(FILENAMESQL, "");\r
 \r
         s = req.getParameter("publishId");\r
         if (s != null) {\r
@@ -270,17 +302,22 @@ public class LogServlet extends BaseServlet {
                 map.put("err", "bad publishId");\r
                 return map;\r
             }\r
-            map.put("publishSQL", " AND PUBLISH_ID = '"+s+"'");\r
+            map.put(PUBLISHSQL, " AND PUBLISH_ID = '"+s+"'");\r
+        }\r
+\r
+        s = req.getParameter("filename");\r
+        if (s != null) {\r
+            map.put(FILENAMESQL, " AND FILENAME = '"+s+"'");\r
         }\r
 \r
         s = req.getParameter("statusCode");\r
         if (s != null) {\r
             String sql = null;\r
-            if (s.equals("success")) {\r
+            if ("success".equals(s)) {\r
                 sql = " AND STATUS >= 200 AND STATUS < 300";\r
-            } else if (s.equals("redirect")) {\r
+            } else if ("redirect".equals(s)) {\r
                 sql = " AND STATUS >= 300 AND STATUS < 400";\r
-            } else if (s.equals("failure")) {\r
+            } else if ("failure".equals(s)) {\r
                 sql = " AND STATUS >= 400";\r
             } else {\r
                 try {\r
@@ -294,21 +331,21 @@ public class LogServlet extends BaseServlet {
                 map.put("err", "bad statusCode");\r
                 return map;\r
             }\r
-            map.put("statusSQL", sql);\r
-            map.put("resultSQL", sql.replaceAll("STATUS", "RESULT"));\r
+            map.put(STATUSSQL, sql);\r
+            map.put(RESULTSQL, sql.replaceAll("STATUS", "RESULT"));\r
         }\r
 \r
         s = req.getParameter("expiryReason");\r
         if (s != null) {\r
             map.put("type", "exp");\r
-            if (s.equals("notRetryable")) {\r
-                map.put("reasonSQL", " AND REASON = 'notRetryable'");\r
-            } else if (s.equals("retriesExhausted")) {\r
-                map.put("reasonSQL", " AND REASON = 'retriesExhausted'");\r
-            } else if (s.equals("diskFull")) {\r
-                map.put("reasonSQL", " AND REASON = 'diskFull'");\r
-            } else if (s.equals("other")) {\r
-                map.put("reasonSQL", " AND REASON = 'other'");\r
+            if ("notRetryable".equals(s)) {\r
+                map.put(REASON_SQL, " AND REASON = 'notRetryable'");\r
+            } else if ("retriesExhausted".equals(s)) {\r
+                map.put(REASON_SQL, " AND REASON = 'retriesExhausted'");\r
+            } else if ("diskFull".equals(s)) {\r
+                map.put(REASON_SQL, " AND REASON = 'diskFull'");\r
+            } else if ("other".equals(s)) {\r
+                map.put(REASON_SQL, " AND REASON = 'other'");\r
             } else {\r
                 map.put("err", "bad expiryReason");\r
                 return map;\r
@@ -333,7 +370,7 @@ public class LogServlet extends BaseServlet {
         } else if (etime == 0) {\r
             etime = stime + TWENTYFOUR_HOURS;\r
         }\r
-        map.put("timeSQL", String.format(" AND EVENT_TIME >= %d AND EVENT_TIME <= %d", stime, etime));\r
+        map.put(TIMESQL, String.format(" AND EVENT_TIME >= %d AND EVENT_TIME <= %d", stime, etime));\r
         return map;\r
     }\r
     private long getTimeFromParam(final String s) {\r
@@ -341,17 +378,18 @@ public class LogServlet extends BaseServlet {
             return 0;\r
         try {\r
             // First, look for an RFC 3339 date\r
-            String fmt = (s.indexOf('.') > 0) ? fmt2 : fmt1;\r
+            String fmt = (s.indexOf('.') > 0) ? FMT_2 : FMT_1;\r
             SimpleDateFormat sdf = new SimpleDateFormat(fmt);\r
             Date d = sdf.parse(s);\r
             return d.getTime();\r
-        } catch (ParseException e) {\r
+        } catch (ParseException parseException) {\r
+            intlogger.error("Exception in getting Time :- "+parseException.getMessage(),parseException);\r
         }\r
         try {\r
             // Also allow a long (in ms); useful for testing\r
-            long n = Long.parseLong(s);\r
-            return n;\r
-        } catch (NumberFormatException e) {\r
+            return Long.parseLong(s);\r
+        } catch (NumberFormatException numberFormatException) {\r
+            intlogger.error("Exception in getting Time :- "+numberFormatException.getMessage(),numberFormatException);\r
         }\r
         intlogger.info("Error parsing time="+s);\r
         return -1;\r
@@ -359,51 +397,51 @@ public class LogServlet extends BaseServlet {
 \r
     private void getPublishRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
         String type = map.get("type");\r
-        if (type.equals("all") || type.equals("pub")) {\r
-            String sql = "select * from LOG_RECORDS where FEEDID = "+feedid\r
+        if ("all".equals(type) || "pub".equals(type)) {\r
+            String sql = LOG_RECORDSSQL+feedid\r
                 + " AND TYPE = 'pub'"\r
-                + map.get("timeSQL") + map.get("publishSQL") + map.get("statusSQL");\r
+                + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(STATUSSQL) + map.get(FILENAMESQL);\r
             getRecordsForSQL(sql, rh);\r
         }\r
     }\r
     private void getDeliveryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
         String type = map.get("type");\r
-        if (type.equals("all") || type.equals("del")) {\r
-            String sql = "select * from LOG_RECORDS where FEEDID = "+feedid\r
+        if ("all".equals(type) || "del".equals(type)) {\r
+            String sql = LOG_RECORDSSQL+feedid\r
                 + " AND TYPE = 'del'"\r
-                + map.get("timeSQL") + map.get("publishSQL") + map.get("resultSQL");\r
+                + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(RESULTSQL);\r
             getRecordsForSQL(sql, rh);\r
         }\r
     }\r
     private void getDeliveryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {\r
         String type = map.get("type");\r
-        if (type.equals("all") || type.equals("del")) {\r
+        if ("all".equals(type) || "del".equals(type)) {\r
             String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = "+subid\r
                 + " AND TYPE = 'del'"\r
-                + map.get("timeSQL") + map.get("publishSQL") + map.get("resultSQL");\r
+                + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(RESULTSQL);\r
             getRecordsForSQL(sql, rh);\r
         }\r
     }\r
     private void getExpiryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
         String type = map.get("type");\r
-        if (type.equals("all") || type.equals("exp")) {\r
-            String st = map.get("statusSQL");\r
+        if ("all".equals(type) || "exp".equals(type)) {\r
+            String st = map.get(STATUSSQL);\r
             if (st == null || st.length() == 0) {\r
-                String sql = "select * from LOG_RECORDS where FEEDID = "+feedid\r
+                String sql = LOG_RECORDSSQL+feedid\r
                     + " AND TYPE = 'exp'"\r
-                    + map.get("timeSQL") + map.get("publishSQL") + map.get("reasonSQL");\r
+                    + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(REASON_SQL);\r
                 getRecordsForSQL(sql, rh);\r
             }\r
         }\r
     }\r
     private void getExpiryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {\r
         String type = map.get("type");\r
-        if (type.equals("all") || type.equals("exp")) {\r
-            String st = map.get("statusSQL");\r
+        if ("all".equals(type) || "exp".equals(type)) {\r
+            String st = map.get(STATUSSQL);\r
             if (st == null || st.length() == 0) {\r
                 String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = "+subid\r
                     + " AND TYPE = 'exp'"\r
-                    + map.get("timeSQL") + map.get("publishSQL") + map.get("reasonSQL");\r
+                    + map.get(TIMESQL) + map.get(PUBLISHSQL) + map.get(REASON_SQL);\r
                 getRecordsForSQL(sql, rh);\r
             }\r
         }\r
@@ -415,15 +453,15 @@ public class LogServlet extends BaseServlet {
         Connection conn = null;\r
         try {\r
             conn = db.getConnection();\r
-            Statement  stmt = conn.createStatement();\r
-            ResultSet rs = stmt.executeQuery(sql);\r
-            while (rs.next()) {\r
-                rh.handleRow(rs);\r
-            }\r
-            rs.close();\r
-            stmt.close();\r
-        } catch (SQLException e) {\r
-            e.printStackTrace();\r
+           try( Statement  stmt = conn.createStatement()){\r
+             try(ResultSet rs = stmt.executeQuery(sql)){\r
+                 while (rs.next()) {\r
+                     rh.handleRow(rs);\r
+                 }\r
+             }\r
+           }\r
+        } catch (SQLException sqlException) {\r
+            intlogger.info("Failed to get Records. Exception = " +sqlException.getMessage(),sqlException);\r
         } finally {\r
             if (conn != null)\r
                 db.release(conn);\r