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