View Javadoc

1   package cz.cuni.amis.utils;
2   
3   import java.io.BufferedReader;
4   import java.io.File;
5   import java.io.FileReader;
6   import java.io.FileWriter;
7   import java.io.IOException;
8   import java.io.PrintWriter;
9   import java.util.regex.Pattern;
10  
11  /**
12   * Simple way how to filter your log files...
13   */
14  public class LogFilter {
15  	
16  	private File source;
17  	private File destination;
18  	private Pattern[] accept;
19  	private Pattern[] remove;
20  
21  
22  
23  	/**
24  	 * Opens 'source', writes to 'destination'.
25  	 * <p><p>
26  	 * Every single line from 'source' is matched against 'accept'. If some pattern matches the line, it goes to 'destination'.<p>
27  	 * If not, it is matched against 'remove'. If some pattern matches the line, it is discarded.<p>
28  	 * If no pattern matches, the line goes to 'destination'.
29  	 * 
30  	 * @param source
31  	 * @param destination
32  	 * @param accept
33  	 * @param remove
34  	 */
35  	public LogFilter(File source, File destination, Pattern[] accept, Pattern[] remove) {
36  		this.source = source;
37  		this.destination = destination;
38  		this.accept = accept;
39  		this.remove = remove;
40  	}
41  
42  	public void filter() throws IOException {
43  		FileReader fileReader = new FileReader(source);
44  		try {
45  			BufferedReader reader = new BufferedReader(fileReader);
46  			FileWriter fileWriter = new FileWriter(destination);
47  			try {
48  				PrintWriter writer = new PrintWriter(fileWriter);
49  				
50  				System.out.println("-= Log filtering =-");
51  				System.out.println("Source: " + source.getAbsolutePath());
52  				System.out.println("Destin: " + destination.getAbsolutePath());				
53  				
54  				int lineCount = 0;
55  				while (reader.ready()) {
56  					boolean next = false;
57  					
58  					System.out.print(".");
59  					++lineCount;
60  					if (lineCount % 100 == 0) System.out.println();
61  					
62  					String line = reader.readLine();
63  					
64  					for (Pattern a : this.accept) {
65  						if (a.matcher(line).find()) {
66  							writer.println(line);
67  							next = true;
68  							break;
69  						}
70  					}
71  					if (next) continue;
72  					
73  					for (Pattern r : this.remove) {
74  						if (r.matcher(line).find()) {						
75  							next = true;
76  							break;
77  						}
78  					}
79  					if (next) continue;
80  										
81  					writer.println(line);					
82  				}
83  				System.out.println();
84  				System.out.println("FINISHED");
85  			} finally {
86  				fileWriter.close();
87  			}
88  		} finally {
89  			fileReader.close();
90  		}
91  		
92  		
93  	}
94  	
95  }