summaryrefslogtreecommitdiffstats
path: root/container-core/src/main/java/com/yahoo/container/handler/LogReader.java
blob: 9ac40158e0781296e1e5f206a0a299c194e521e4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.yahoo.container.handler;

import org.json.JSONException;
import org.json.JSONObject;

import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Comparator;

public class LogReader {

    int numberOfLogs;

    public LogReader() {
        this.numberOfLogs = -1;
    }

    public LogReader(int numberOfLogs) {
        this.numberOfLogs = numberOfLogs;
    }

    protected JSONObject readLogs(String logDirectory) throws IOException, JSONException {
        JSONObject json = new JSONObject();
        File root = new File(logDirectory);
        traverse_folder(root, json);
        return json;
    }

    private void traverse_folder(File root, JSONObject json) throws IOException, JSONException {
        File[] files = root.listFiles();
        Arrays.sort(files,new Comparator<File>(){
            public int compare(File f1, File f2)
            {
                return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
            } });
        Arrays.sort(files, Comparator.reverseOrder());
        for(File child : files) {
            if (numberOfLogs == 0) return;
            JSONObject childJson = new JSONObject();
            if(child.isFile()) {
                json.put(child.getName(), DatatypeConverter.printBase64Binary(Files.readAllBytes(child.toPath())));
                decrementLogNumber();
            }
            else {
                json.put(child.getName(), childJson);
                traverse_folder(child, childJson);
            }
        }
    }

    private void decrementLogNumber() {
        numberOfLogs -= 1;
    }

}