My problem is in my readFiles()
method where I am creating ArrayList<LogEntry>
records.
public class LogAnalyzer {
private static ArrayList<LogEntry> records;
static ReadJavaDoc obj = new ReadJavaDoc();
public LogAnalyzer() {
records = new ArrayList<LogEntry>();
}
public static void readFiles(String str) throws FileNotFoundException {
for (String s : obj.linesOfFile(str)) {
LogEntry entry = WebLogParser.parseEntry(s);
records.add(entry);
}
for (LogEntry i : records) {
System.out.println(i);
}
}
public static void main(String[] args) throws FileNotFoundException {
new LogAnalyzer();
readFiles(filePath);
}
}
I have a toString()
method in my LogEntry
and by looping over, I was expecting each entry to be printed on a separate line.
However, only the last object got printed 7 times.
Other classes:
public class WebLogParser {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MMM/yyyy:kk:mm:ss Z", Locale.US);
private static String munchTo(StringBuilder sb, String delim) {
int x = sb.indexOf(delim);
if (x == -1) {
x = sb.length();
}
String ans = sb.substring(0,x);
sb.delete(0, x + delim.length());
return ans;
}
public static LogEntry parseEntry(String line) {
//Assumes line is vald and in this format:
//110.76.104.12 - - [30/Sep/2015:07:47:11 -0400] "GET //favicon.ico HTTP/1.1" 200 3426
StringBuilder sb = new StringBuilder(line);
String ip = munchTo(sb, " ");
munchTo(sb, " "); //ignore -
munchTo(sb, " ["); //ignore -, and eat the leading [
String dateStr = munchTo(sb, "] \""); //]-space is intentional: eat both
Date date = parseDate(dateStr);
String request = munchTo(sb, "\" "); // quote-space is intentional: eat both
String statusStr = munchTo(sb, " ");
int status = Integer.parseInt(statusStr);
String byteStr = munchTo(sb, " ");
int bytes = Integer.parseInt(byteStr);
return new LogEntry(ip, request, status, bytes, date);
}
public static Date parseDate(String dateStr) {
ParsePosition pp = new ParsePosition(0);
return dateFormat.parse(dateStr, pp);
}}
public class LogEntry {
private static String ipAddress;
private static String request;
private static int statusCode;
private static int bytesReturned;
private static Date accessTime;
public LogEntry(String ip, String req, int stCode, int bytes, Date accTime) {
ipAddress = ip;
request = req;
statusCode = stCode;
bytesReturned = bytes;
accessTime = accTime;
}
public static String getIp() {
return ipAddress;
}
public static String getRequest() {
return request;
}
public static int getStatusCode() {
return statusCode;
}
public static int getBytesReturned() {
return bytesReturned;
}
public static Date getAccessTime() {
return accessTime;
}
public String toString() {
return ipAddress + " " + request + " " + statusCode + " " + accessTime + " " + bytesReturned;
}
}