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 | // Parse a /var/log/auth.log file; Nov 2015; Ex of Streams, Lambdas
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class AuthLogStreamEx {
private void grep(String inpfnm, String outfnm)
throws IOException {
Stream<String> lns = Files.lines(Paths.get(inpfnm));
FileWriter fw = new FileWriter(outfnm);
//@formatter:off
lns
.filter(ln -> ln.contains("Invalid user"))
.map(ln -> ln.split(" "))
.map(arr -> arr[arr.length - 1]) // keep the last item
.forEach(ip -> writeToFile(fw, ip)); // could do better
//@formatter:on
fw.close();
lns.close();
}
private int pn = 0;
private void writeToFile(FileWriter fw, String s) {
try {
fw.write(String.format("%d %s\n", ++pn, s));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws IOException {
String ifnm = "/var/log/auth.log", ofnm = "/tmp/invalidUsers.txt";
switch (args.length) {
case 0: break;
case 2: ofnm = args[1]; // fall through
case 1: ifnm = args[0]; break;
default:
System.out.println
("StreamEx Usage: At most two file names expected");
System.exit(0);
}
new AuthLogStreamEx().grep(ifnm, ofnm);
}
}
// -eof-
|