75ccfd47779d6565066f11b5631e71a9ab2bbbb3
[policy/engine.git] / LogParser / src / main / java / org / onap / xacml / parser / ParseLog.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * LogParser
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.xacml.parser;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.FileReader;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.LineNumberReader;
29 import java.io.RandomAccessFile;
30 import java.nio.charset.Charset;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.sql.Connection;
35 import java.sql.DriverManager;
36 import java.sql.PreparedStatement;
37 import java.sql.SQLException;
38 import java.text.Format;
39 import java.text.ParseException;
40 import java.text.SimpleDateFormat;
41 import java.util.Date;
42 import java.util.Properties;
43 import java.util.Timer;
44 import java.util.regex.Matcher;
45 import java.util.regex.Pattern;
46 import java.util.stream.Stream;
47
48 import org.apache.log4j.Logger;
49 import org.onap.policy.common.im.IntegrityMonitor;
50 import org.onap.policy.common.im.IntegrityMonitorException;
51 import org.onap.policy.common.logging.flexlogger.FlexLogger;
52 import org.onap.policy.utils.CryptoUtils;
53 import org.onap.xacml.parser.LogEntryObject.LogType;
54
55 /**
56  * Parse log files and store the information in a H2 database.
57  *
58  *
59  */
60 public class ParseLog {
61
62     // only logging last line of each log file processed to the log4j log file defined by property - PARSERLOGPATH
63     private static final Logger log4jlogger = Logger.getLogger(ParseLog.class.getName());
64
65     // processing logging
66     private static org.onap.policy.common.logging.flexlogger.Logger logger =
67             FlexLogger.getLogger(ParseLog.class.getName());
68
69     private static String system;
70     private static int lastNumberRead = 0;
71     private static int debuglastNumberRead = 0;
72     private static int errorlastNumberRead = 0;
73     private static String type;
74     private static long startFileSize;
75     private static long debugStartFileSize;
76     private static long errorStartFileSize;
77     private static String systemLogFile;
78     private static String logFile;
79     private static String debuglogFile;
80     private static String errorlogFile;
81     private static String jdbcUrl;
82     private static String jdbcUser;
83     private static String jdbcPassword;
84     private static String jdbcDriver;
85     private static int maxLength = 255; // Max length that is allowed in the DB table
86     private static String resourceName;
87     private static long sleepTimer = 50000;
88     static IntegrityMonitor im;
89     private static boolean isMissingLogFile;
90     // Default:Timer initial delay and the delay between in milliseconds before task is to be execute
91     private static final int TIMER_DELAY_TIME = 1000;
92     // Default:Timer scheduleAtFixedRate period - time in milliseconds between successive task executions
93     private static int checkInterval = 86400000; // run this clean up once a day
94     private static String loggingProcess = "Error processing line in ";
95     private static int defaultTimeFrame = 5;
96     private static String message = " value read in: ";
97     private static String lineFormat = "(\\r\\n|\\n)";
98     private static String lineRead = "-line-Read:";
99     private static String br = "<br />";
100     private static String last = "Last-";
101     private static String breakLoop = "break the loop.";
102     private static String dateFormat = "yyyy-MM-dd HH:mm:ss";
103
104     /**
105      * The main method to start log parsing.
106      *
107      * @param args the arguments
108      * @throws Exception if an error occurs
109      */
110     public static void main(final String[] args) throws Exception {
111
112         final Properties logProperties = getPropertiesValue("parserlog.properties");
113
114         if (logProperties == null || isMissingLogFile) {
115             // missing the path of log file in the properties file, so stop the process
116             logger.error("logProperties is null or LOGPATH is missing in parserlog.properties, so stop the process.");
117             return;
118         }
119
120         // trigger the cleanup systemLogDb timer
121         startCleanUp();
122
123         final File fileLog = new File(systemLogFile);
124
125         im = IntegrityMonitor.getInstance(resourceName, logProperties);
126
127         startDebugLogParser(fileLog);
128         startErrorLogParser(fileLog);
129         startApiRestLogParser(fileLog);
130
131     }
132
133     private static boolean processLine(final Path debugfilePath, final String dataFileName, final int lastNmRead,
134             final LogType logType) {
135         // log4jlogger must use .info
136         try (Stream<String> lines = Files.lines(debugfilePath, Charset.defaultCharset())
137                 .onClose(() -> log4jlogger.info(last + dataFileName + lineRead + lastNmRead)).skip(lastNmRead)) {
138             lines.forEachOrdered(line -> process(line, type, logType));
139         } catch (final IOException e) {
140             logger.error(loggingProcess + dataFileName, e);
141             logger.error(breakLoop);
142             return true;
143         }
144         return false;
145     }
146
147     private static void processDebugLogParser(final File debugfile, final Path debugfilePath,
148             final String dataFileName) {
149
150         final Runnable runnable = new Runnable() {
151             boolean isStop = false;
152
153             @Override
154             public void run() {
155                 while (!isStop) {
156                     if (debugfile.isFile()) {
157                         isStop = processLine(debugfilePath, dataFileName, debuglastNumberRead, LogType.DEBUG);
158                     }
159                     try {
160                         Thread.sleep(sleepTimer);
161                         debugStartFileSize = countLines(debuglogFile);
162                     } catch (final Exception e) {
163                         logger.error(loggingProcess + dataFileName, e);
164                         logger.error(breakLoop);
165                         isStop = true;
166                     }
167                     logger.debug("File Line Count of debug.log: " + debugStartFileSize + message + debuglastNumberRead);
168                     if (debugStartFileSize < debuglastNumberRead) {
169                         logger.debug("Failed Rolled: set Last number read to 0");
170                         debuglastNumberRead = 0;
171                     }
172                 }
173             }
174         };
175
176         final Thread thread = new Thread(runnable);
177         thread.start();
178     }
179
180     private static void startDebugLogParser(final File fileLog) throws IOException {
181
182         if (debuglogFile != null && !debuglogFile.isEmpty()) {
183
184             // pull the last line number
185             final String dataFileName = "debug.log";
186             String filesRead = pullLastLineRead(fileLog, dataFileName);
187             if (filesRead != null) {
188                 filesRead = filesRead.replaceAll(lineFormat, br);
189                 debuglastNumberRead = Integer.parseInt(filesRead.trim());
190             } else {
191                 debuglastNumberRead = 0;
192             }
193
194             debugStartFileSize = countLines(debuglogFile);
195             if (debugStartFileSize < debuglastNumberRead) {
196                 logger.error("Filed Rolled: set Last debug number read to 0");
197                 debuglastNumberRead = 0;
198             }
199
200             isMissingLogFile = false;
201             final Path debugfilePath = Paths.get(debuglogFile);
202             final File debugfile = new File(debuglogFile);
203             debugStartFileSize = debugfile.length();
204
205             // start process debug.log file
206             processDebugLogParser(debugfile, debugfilePath, dataFileName);
207
208         }
209     }
210
211     private static void processErrorLogParser(final File errorfile, final Path errorfilePath,
212             final String dataFileName) {
213         final Runnable runnable = new Runnable() {
214             boolean isStop = false;
215
216             @Override
217             public void run() {
218
219                 while (!isStop) {
220                     if (errorfile.isFile()) {
221                         isStop = processLine(errorfilePath, dataFileName, errorlastNumberRead, LogType.ERROR);
222                     }
223                     try {
224                         Thread.sleep(sleepTimer);
225                         errorStartFileSize = countLines(errorlogFile);
226                     } catch (final Exception e) {
227                         logger.error(loggingProcess + dataFileName, e);
228                         logger.error(breakLoop);
229                         isStop = true;
230                     }
231
232                     logger.debug("File Line Count of error.log: " + errorStartFileSize + message + errorlastNumberRead);
233                     if (errorStartFileSize < errorlastNumberRead) {
234                         logger.debug("Failed Rolled: set Last error number read to 0");
235                         errorlastNumberRead = 0;
236                     }
237                 }
238             }
239         };
240
241         final Thread thread = new Thread(runnable);
242         thread.start();
243     }
244
245     private static void startErrorLogParser(final File fileLog) throws IOException {
246
247         if (errorlogFile != null && !errorlogFile.isEmpty()) {
248
249             // pull the last line number
250             final String dataFileName = "error.log";
251             String filesRead = pullLastLineRead(fileLog, dataFileName);
252             if (filesRead != null) {
253                 filesRead = filesRead.replaceAll(lineFormat, br);
254                 errorlastNumberRead = Integer.parseInt(filesRead.trim());
255             } else {
256                 errorlastNumberRead = 0;
257             }
258
259             errorStartFileSize = countLines(errorlogFile);
260             if (errorStartFileSize < errorlastNumberRead) {
261                 logger.error("Filed Rolled: set Last error number read to 0");
262                 errorlastNumberRead = 0;
263             }
264
265             isMissingLogFile = false;
266             final Path errorfilePath = Paths.get(errorlogFile);
267             final File errorfile = new File(errorlogFile);
268             errorStartFileSize = errorfile.length();
269             // start process error.log file
270             processErrorLogParser(errorfile, errorfilePath, dataFileName);
271
272         }
273     }
274
275     private static void processApiRestLog(final File file, final Path filePath, final String dataFileName) {
276
277         final Runnable runnable = new Runnable() {
278             boolean isStop = false;
279
280             @Override
281             public void run() {
282                 while (!isStop) {
283
284                     if (file.isFile()) {
285                         isStop = processLine(filePath, dataFileName, lastNumberRead, LogType.INFO);
286                     }
287                     try {
288                         Thread.sleep(sleepTimer);
289                         startFileSize = countLines(logFile);
290                     } catch (final Exception e) {
291                         logger.error(loggingProcess + dataFileName, e);
292                         logger.error(breakLoop);
293                         isStop = true;
294                     }
295
296                     logger.debug(
297                             "File Line Count of " + dataFileName + ": " + startFileSize + message + lastNumberRead);
298                     if (startFileSize < lastNumberRead) {
299                         logger.debug("Failed Rolled: set Last number read to 0");
300                         lastNumberRead = 0;
301                     }
302                 }
303             }
304         };
305
306         final Thread thread = new Thread(runnable);
307         thread.start();
308     }
309
310     private static void startApiRestLogParser(final File fileLog) throws IOException {
311
312         if (logFile != null && !logFile.isEmpty()) {
313
314             // pull the last line number
315             final String dataFileName = type.toLowerCase() + "-rest.log";
316             String filesRead = pullLastLineRead(fileLog, dataFileName);
317             if (filesRead != null) {
318                 filesRead = filesRead.replaceAll(lineFormat, br);
319                 lastNumberRead = Integer.parseInt(filesRead.trim());
320             } else {
321                 lastNumberRead = 0;
322             }
323             startFileSize = countLines(logFile);
324             if (startFileSize < lastNumberRead) {
325                 logger.error("Filed Rolled: set Last number read to 0");
326                 lastNumberRead = 0;
327             }
328
329             isMissingLogFile = false;
330             final Path filePath = Paths.get(logFile);
331             final File file = new File(logFile);
332             startFileSize = file.length();
333             // start process pap/pdp-rest.log file
334             processApiRestLog(file, filePath, dataFileName);
335         }
336     }
337
338     /**
339      * Count the number of lines in input file.
340      *
341      * @param filename the filename
342      * @return the lines count
343      */
344     public static int countLines(final String filename) {
345         int cnt = 0;
346         try (FileReader freader = new FileReader(filename); LineNumberReader reader = new LineNumberReader(freader)) {
347             String line = null;
348             while ((line = reader.readLine()) != null) {
349                 logger.debug("Reading the Logs" + line);
350             }
351             cnt = reader.getLineNumber();
352             logger.info("Line number:" + cnt);
353             reader.close();
354             freader.close();
355
356         } catch (final Exception e) {
357             logger.error(e);
358         }
359
360         return cnt;
361     }
362
363     /**
364      * Get the last line read from the input file if exists.
365      *
366      * @param file the file
367      * @param dataFileName the data file name
368      * @return last line read or null
369      * @throws IOException if any error occurs
370      */
371     public static String pullLastLineRead(final File file, final String dataFileName) throws IOException {
372         if (!file.exists()) {
373             file.createNewFile();
374             return null;
375         }
376         try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");) {
377             StringBuilder builder = new StringBuilder();
378             long length = file.length();
379             logger.debug("dataFileName: " + dataFileName);
380             if (length > 0) {
381                 length--;
382                 randomAccessFile.seek(length);
383                 for (long seek = length; seek >= 0; --seek) {
384                     randomAccessFile.seek(seek);
385                     final char c = (char) randomAccessFile.read();
386                     builder.append(c);
387                     if (c == '\n') {
388                         builder = builder.reverse();
389                         logger.debug("builder.toString(): " + builder.toString());
390                         if (builder.toString().contains(last + dataFileName + lineRead)) {
391                             final String[] parseString = builder.toString().split(last + dataFileName + lineRead);
392                             final String returnValue = parseString[1].replace("\r", "");
393                             randomAccessFile.close();
394                             return returnValue.trim();
395                         }
396                         builder = new StringBuilder();
397                     }
398                 }
399             }
400             randomAccessFile.close();
401         }
402         return null;
403     }
404
405     private static LogEntryObject getDebugOutLogValue(final String line, final String type) {
406
407         Date date;
408         final LogEntryObject logEntry = new LogEntryObject();
409         logEntry.setSystemType(type);
410         logEntry.setSystem(system);
411         final String info1 = "||INFO||";
412         final String info2 = "INFO:";
413         final String error1 = "||ERROR||";
414         final String error2 = "ERROR:";
415
416         if (line.contains(info1) || line.contains(error1) || line.contains(info2) || line.contains(error2)) {
417             String[] splitString = null;
418             if (line.contains(info1) || line.contains(error1)) {
419                 splitString = line.split("[||]");
420             } else if (line.contains(info2)) {
421                 splitString = line.split(info2);
422             } else {
423                 splitString = line.split(error2);
424             }
425             final String dateString = splitString[0].substring(0, 19);
426             logEntry.setDescription(splitString[splitString.length - 1]);
427
428             // parse out date
429             date = parseDate(dateString.replace("T", " "), dateFormat, false);
430             logEntry.setDate(date);
431
432             logEntry.setRemote(parseRemoteSystem(line));
433             if (line.contains(info2) || line.contains(info1)) {
434                 logEntry.setLogType(LogType.INFO);
435             } else {
436                 logEntry.setLogType(LogType.ERROR);
437             }
438
439             return logEntry;
440         }
441
442         return null;
443     }
444
445     private static LogEntryObject getRestApiOutLogValue(final String line, final String type) {
446         Date date;
447         final LogEntryObject logEntry = new LogEntryObject();
448         logEntry.setSystemType(type);
449         logEntry.setSystem(system);
450         final String info3 = "INFO";
451
452         // from PDP/PAP rest log file below
453         if (line.contains(info3) && line.contains(")-")) {
454             // parse out description
455             logEntry.setDescription(line.substring(line.indexOf(")-") + 3));
456
457             date = parseDate(line, dateFormat, true);
458             logEntry.setDate(date);
459
460             logEntry.setRemote(parseRemoteSystem(line));
461             logEntry.setLogType(LogType.INFO);
462
463             return logEntry;
464         }
465
466         return null;
467     }
468
469     private static LogEntryObject getInfoOutLogValue(final String line, final String type) {
470         Date date;
471         final LogEntryObject logEntry = new LogEntryObject();
472         logEntry.setSystemType(type);
473         logEntry.setSystem(system);
474         final String info3 = "INFO";
475
476         if (line.contains(info3) && line.contains("--- [")) {
477             // parse out description
478             final String temp = line.substring(line.indexOf("---") + 1);
479             final String[] split = temp.split(":");
480
481             logEntry.setDescription(split[1]);
482
483             // parse out date
484             date = parseDate(line, dateFormat, false);
485             logEntry.setDate(date);
486
487             // remote system
488             logEntry.setRemote(parseRemoteSystem(line));
489             logEntry.setLogType(LogType.INFO);
490
491             return logEntry;
492         }
493
494         return null;
495
496     }
497
498     private static LogEntryObject getSevereOutLogValue(final String line, final String type) {
499         Date date;
500         final LogEntryObject logEntry = new LogEntryObject();
501         logEntry.setSystemType(type);
502         logEntry.setSystem(system);
503         if (line.contains("SEVERE") && line.contains("[main]")) {
504             final String[] splitString = line.split(" ");
505             final StringBuilder description = new StringBuilder();
506             for (int i = 5; i < splitString.length; i++) {
507                 description.append(" " + splitString[i]);
508             }
509
510             logEntry.setDescription(description.toString());
511             // parse out date
512             date = parseDate(line, dateFormat, false);
513             logEntry.setDate(date);
514             logEntry.setLogType(LogType.SEVERE);
515
516             return logEntry;
517         }
518
519         if (line.contains("ERROR") && line.contains(")-")) {
520             // parse out description
521             final StringBuilder description = new StringBuilder();
522             description.append(line.substring(line.indexOf(")-") + 3));
523             // parse out date
524             date = parseDate(line, dateFormat, true);
525             logEntry.setDate(date);
526             logEntry.setDescription(description.toString());
527             // remote system
528             logEntry.setRemote(parseRemoteSystem(line));
529             logEntry.setLogType(LogType.ERROR);
530
531             return logEntry;
532         }
533
534         return null;
535     }
536
537     private static LogEntryObject getWarnOutLogValue(final String line, final String type) {
538         Date date;
539         final LogEntryObject logEntry = new LogEntryObject();
540         logEntry.setSystemType(type);
541         logEntry.setSystem(system);
542         if (line.contains("WARN") && line.contains(")-")) {
543             // parse out description
544
545             logEntry.setDescription(line.substring(line.indexOf(")-") + 3));
546
547             // parse out date
548             date = parseDate(line, dateFormat, true);
549             logEntry.setDate(date);
550
551             // remote system
552             logEntry.setRemote(parseRemoteSystem(line));
553             logEntry.setLogType(LogType.WARN);
554
555             return logEntry;
556         }
557
558         if (line.contains("WARNING") && type == "PyPDP") {
559             final String[] splitString = line.split(" ");
560             final StringBuilder description = new StringBuilder();
561
562             for (int i = 5; i < splitString.length; i++) {
563                 description.append(" " + splitString[i]);
564             }
565
566             // parse out date
567             date = parseDate(line, dateFormat, false);
568             logEntry.setDate(date);
569             logEntry.setLogType(LogType.WARN);
570             logEntry.setDescription(description.toString());
571             return logEntry;
572         }
573
574         return null;
575
576     }
577
578     /**
579      * Get log values based on provided line and type.
580      *
581      * @param line the line
582      * @param type the type
583      * @return {@link LogEntryObject}
584      */
585     public static LogEntryObject pullOutLogValues(final String line, final String type) {
586
587         LogEntryObject logEntry = getDebugOutLogValue(line, type);
588
589         if (logEntry == null) {
590             logEntry = getRestApiOutLogValue(line, type);
591         }
592         if (logEntry == null) {
593             logEntry = getInfoOutLogValue(line, type);
594         }
595         if (logEntry == null) {
596             logEntry = getSevereOutLogValue(line, type);
597         }
598         if (logEntry == null) {
599             logEntry = getWarnOutLogValue(line, type);
600         }
601
602         return logEntry;
603     }
604
605     private static void dbClose(final Connection conn) {
606         try {
607             conn.close();
608         } catch (final SQLException e) {
609             logger.error("Error closing DB Connection: " + e);
610
611         }
612     }
613
614     /**
615      * Process the provided line, type and log file.
616      *
617      * @param line the line
618      * @param type the type
619      * @param logFile the log type
620      */
621     public static void process(final String line, final String type, final LogType logFile) {
622
623         LogEntryObject returnLogValue = null;
624         if (im != null) {
625             try {
626                 im.startTransaction();
627             } catch (final IntegrityMonitorException e) {
628                 logger.error("Error received" + e);
629             }
630         }
631         returnLogValue = pullOutLogValues(line, type);
632
633         if (logFile.equals(LogType.DEBUG)) {
634             debuglastNumberRead++;
635         } else if (logFile.equals(LogType.ERROR)) {
636             errorlastNumberRead++;
637         } else if (logFile.equals(LogType.INFO)) {
638             lastNumberRead++;
639         }
640         if (returnLogValue != null) {
641             writeDb(returnLogValue);
642         }
643         if (im != null) {
644             im.endTransaction();
645         }
646     }
647
648     private static void writeDb(final LogEntryObject returnLogValue) {
649
650         final Connection conn = dbConnection(jdbcDriver, jdbcUrl, jdbcUser, jdbcPassword);
651         dbAccesss(conn, returnLogValue.getSystem(), returnLogValue.getDescription(), returnLogValue.getDate(),
652                 returnLogValue.getRemote(), returnLogValue.getSystemType(), returnLogValue.getLogType().toString());
653         dbClose(conn);
654     }
655
656     private static Connection dbConnection(final String driver, final String jdbc, final String user,
657             final String pass) {
658
659         try {
660             Class.forName(driver);
661             return DriverManager.getConnection(jdbc, user, pass);
662         } catch (final Exception e) {
663             logger.error("Error connecting to DB: " + e);
664         }
665         return null;
666     }
667
668     private static void dbAccesss(final Connection conn, final String system, String description, final Date date,
669             final String remote, final String type, final String logType) {
670
671         String sdate = null;
672         if (date != null) {
673             final Format formatter = new SimpleDateFormat(dateFormat);
674             sdate = formatter.format(date);
675             logger.debug("DBAccesss : sdate : " + sdate);
676         } else {
677             logger.debug("DBAccesss : sdate is null");
678         }
679
680         // ensure the length of description is less than the maximumm db char length
681         if (description.length() > maxLength) {
682             description = description.substring(0, maxLength);
683         }
684
685         try (PreparedStatement prep =
686                 conn.prepareStatement("insert into SYSTEMLOGDB values (NULL, ?, ?, ?,  ?,  ?, ?);");) {
687
688             prep.setString(1, system);
689             prep.setString(2, description);
690             prep.setString(3, remote);
691             prep.setString(4, type);
692             prep.setString(5, sdate);
693             prep.setString(6, logType);
694
695             prep.executeUpdate();
696             prep.close();
697
698         } catch (final SQLException e1) {
699             logger.error("Error trying to excute SQL Statment: " + e1);
700         }
701     }
702
703     /**
704      * Parse the given date string based on the provided pattern with/without split based on input boolean value.
705      *
706      * @param dateline the date string
707      * @param pattern the provided pattern
708      * @param singleSplit the single split boolean value
709      * @return the parsed date or null
710      */
711     public static Date parseDate(final String dateline, final String pattern, final boolean singleSplit) {
712
713         Date returnDate;
714         final String[] splitString = dateline.split(" ");
715         final SimpleDateFormat formatter = new SimpleDateFormat(pattern);
716         if (singleSplit) {
717             try {
718                 returnDate = formatter.parse(dateline);
719             } catch (final ParseException e) {
720                 logger.error("Unable to parse date for line: " + dateline);
721                 returnDate = null;
722             }
723         } else {
724             final String tmpString = splitString[0] + " " + splitString[1];
725             try {
726                 returnDate = formatter.parse(tmpString);
727             } catch (final ParseException e) {
728                 logger.error("Unable to parse date for line: " + dateline);
729                 returnDate = null;
730             }
731         }
732
733         return returnDate;
734     }
735
736
737     /**
738      * Get remote system host from given string if exists.
739      *
740      * @param line the input string
741      * @return system host or null
742      */
743     public static String parseRemoteSystem(final String line) {
744
745         if (line.contains("http") && !(line.contains("www.w3.org"))) {
746
747             final Pattern pattern = Pattern.compile("://(.+?)/");
748             final Matcher remote = pattern.matcher(line);
749             if (remote.find()) {
750                 return remote.group(1);
751             }
752         }
753         return null;
754     }
755
756     /**
757      * Get the log paths provided in input string.
758      *
759      * @param logPath the string of log paths
760      * @return log paths
761      */
762     public static String[] getPaths(final String logPath) {
763         String[] oneFile = null;
764         if (logPath != null && !logPath.isEmpty()) {
765             if (logPath.contains(";")) {
766                 return logPath.split(";");
767             } else {
768                 oneFile = new String[1];
769                 oneFile[0] = logPath;
770             }
771         }
772
773         return oneFile;
774     }
775
776     private static void setCleanUpProperties(final String cleanupInterval, final String timeFrame) {
777         if (cleanupInterval != null && !cleanupInterval.isEmpty()) {
778             final int intCheckInterval = Integer.parseInt(cleanupInterval);
779             if (intCheckInterval > 300000) { // must be longer than 5 minutes
780                 checkInterval = intCheckInterval;
781             }
782         } else {
783             logger.debug("No value defined for CHECK_INTERVAL in parserlog.properties, so use its default value:"
784                     + checkInterval + " milliseconds");
785         }
786
787         if (timeFrame != null && !timeFrame.trim().isEmpty()) {
788             int intTimeFrame = defaultTimeFrame;
789             try {
790                 intTimeFrame = Integer.parseInt(timeFrame);
791             } catch (final NumberFormatException e) {
792                 logger.debug("Improper value defined for TIME_FRAME in parserlog.properties, so use its default value:"
793                         + defaultTimeFrame + " days");
794             }
795             if (intTimeFrame > 0) {
796                 defaultTimeFrame = intTimeFrame;
797             }
798         } else {
799             logger.debug("No value defined for TIME_FRAME in parserlog.properties, so use its default value:"
800                     + defaultTimeFrame + " days");
801         }
802     }
803
804     private static void setDebuglogFile(final String fileName) {
805         debuglogFile = fileName;
806         if (debuglogFile != null && !debuglogFile.isEmpty()) {
807             debuglogFile = debuglogFile.trim();
808         } else {
809             debuglogFile = null;
810         }
811     }
812
813     private static void setErrorlogFile(final String fileName) {
814         errorlogFile = fileName;
815         if (errorlogFile != null && !errorlogFile.isEmpty()) {
816             errorlogFile = errorlogFile.trim();
817         } else {
818             errorlogFile = null;
819         }
820     }
821
822     private static void setLogFileProperties(final String[] splitString) {
823         if (splitString != null) {
824             for (int i = 0; i < splitString.length; i++) {
825
826                 if (splitString[i].contains("debug")) {
827                     // get path of debug.log file
828                     setDebuglogFile(splitString[i]);
829                 } else if (splitString[i].contains("error")) {
830                     // get path of error.log file
831                     setErrorlogFile(splitString[i]);
832                 } else {
833                     // get path of default file
834                     logFile = splitString[i];
835                     if (logFile != null && !logFile.isEmpty()) {
836                         logFile = logFile.trim();
837                     } else {
838                         logFile = null;
839                     }
840                 }
841             }
842         }
843     }
844
845     /**
846      * Get all the properties from file with given file name.
847      *
848      * @param fileName the filename
849      * @return properties from file or null
850      */
851     public static Properties getPropertiesValue(final String fileName) {
852         final Properties config = new Properties();
853         final Path file = Paths.get(fileName);
854         if (file.toFile().exists()) {
855
856             if (file.toString().endsWith(".properties")) {
857                 InputStream in;
858                 try {
859                     in = new FileInputStream(file.toFile());
860                     config.load(in);
861
862                     resourceName = config.getProperty("RESOURCE_NAME");
863                     system = config.getProperty("SERVER");
864                     type = config.getProperty("LOGTYPE");
865                     systemLogFile = config.getProperty("PARSERLOGPATH");
866                     final String logFiles = config.getProperty("LOGPATH");
867                     final String cleanupInterval = config.getProperty("CHECK_INTERVAL");
868                     final String timeFrame = config.getProperty("TIME_FRAME");
869
870                     setCleanUpProperties(cleanupInterval, timeFrame);
871
872                     if (logFiles == null || logFiles.isEmpty()) {
873                         isMissingLogFile = true;
874                         return null;
875                     }
876
877                     final String[] splitString = getPaths(logFiles);
878
879                     setLogFileProperties(splitString);
880
881                     jdbcUrl = config.getProperty("JDBC_URL").replace("'", "");
882                     jdbcUser = config.getProperty("JDBC_USER");
883                     jdbcDriver = config.getProperty("JDBC_DRIVER");
884                     jdbcPassword = CryptoUtils.decryptTxtNoExStr(config.getProperty("JDBC_PASSWORD", ""));
885                     config.setProperty("javax.persistence.jdbc.password",
886                             CryptoUtils.decryptTxtNoExStr(config.getProperty("javax.persistence.jdbc.password", "")));
887                     return config;
888
889                 } catch (final IOException e) {
890                     logger.error("Error porcessing Config file will be unable to create Health Check" + e);
891                 } catch (final Exception e) {
892                     logger.error("Error getPropertiesValue on TIME_FRAME", e);
893                     logger.debug("Error getPropertiesValue on TIME_FRAME, so use its default value:" + defaultTimeFrame
894                             + " days");
895                 }
896             }
897
898         } else {
899
900             logger.debug("File doesn't exist in the specified Path " + file.toString());
901         }
902         return null;
903     }
904
905     public static Connection getDbConnection() {
906         return dbConnection(jdbcDriver, jdbcUrl, jdbcUser, jdbcPassword);
907     }
908
909     private static void startCleanUp() {
910         final Connection conn = dbConnection(jdbcDriver, jdbcUrl, jdbcUser, jdbcPassword);
911         final CleanUpSystemLogDb cleanUp = new CleanUpSystemLogDb(conn, defaultTimeFrame);
912         final Timer timer = new Timer(true);
913         timer.scheduleAtFixedRate(cleanUp, TIMER_DELAY_TIME, checkInterval);
914         logger.info("startCleanUp begins! : " + new Date());
915     }
916 }