1 package org.djutils.traceverifier;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.Closeable;
6 import java.io.File;
7 import java.io.FileReader;
8 import java.io.FileWriter;
9 import java.io.IOException;
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 public class TraceVerifier implements Closeable
28 {
29
30 private final String outputFileName;
31
32
33 private final BufferedReader reader;
34
35
36
37
38
39
40 public TraceVerifier(final String fileName) throws IOException
41 {
42
43 File traceFile = new File(fileName);
44 if (traceFile.exists())
45 {
46
47 this.reader = new BufferedReader(new FileReader(fileName));
48 this.outputFileName = null;
49 }
50 else
51 {
52
53 this.outputFileName = fileName;
54 BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
55 writer.close();
56 this.reader = null;
57 }
58 }
59
60
61
62
63
64
65
66
67 public void sample(final String description, final String state) throws IOException
68 {
69 String got = String.format("%s: %s", description, state);
70 if (this.reader != null)
71 {
72 String expected = this.reader.readLine();
73 if (expected.equals(got))
74 {
75 return;
76 }
77 int indexOfFirstDifference = 0;
78 while (got.charAt(indexOfFirstDifference) == expected.charAt(indexOfFirstDifference))
79 {
80 indexOfFirstDifference++;
81 }
82 String format =
83 indexOfFirstDifference == 0 ? "Discrepancy found.\n%%-8.8s: \"%%s\"\n%%-8.8s: \"%%s\"\n%%-8.8s: %%s^"
84 : String.format("Discrepancy found.\n%%-8.8s: \"%%s\"\n%%-8.8s: \"%%s\"\n%%-8.8s: %%%d.%ds^",
85 indexOfFirstDifference, indexOfFirstDifference);
86 String error = String.format(format, "Got", got, "Expected", expected, "1st diff", "");
87 throw new TraceVerifierException(error);
88 }
89 BufferedWriter writer = new BufferedWriter(new FileWriter(this.outputFileName, true));
90 writer.append(got);
91 writer.append('\n');
92 writer.close();
93 }
94
95 @Override
96 public void close() throws IOException
97 {
98 if (null != this.reader)
99 {
100 this.reader.close();
101 }
102 }
103
104 @Override
105 public String toString()
106 {
107 return "TraceVerifier [reader=" + this.reader + ", outputFileName=" + this.outputFileName + "]";
108 }
109
110 }