01: package org.slf4j.migrator;
02:
03: import java.io.BufferedReader;
04: import java.io.ByteArrayInputStream;
05: import java.io.ByteArrayOutputStream;
06: import java.io.File;
07: import java.io.FileInputStream;
08: import java.io.FileOutputStream;
09: import java.io.IOException;
10: import java.io.InputStreamReader;
11: import java.io.OutputStream;
12: import java.io.Reader;
13:
14: import org.slf4j.migrator.internal.ProgressListener;
15: import org.slf4j.migrator.line.LineConverter;
16: import org.slf4j.migrator.line.RuleSet;
17:
18: public class InplaceFileConverter {
19:
20: final static int BUFFER_LEN = 8 * 1024;
21: final LineConverter lineConverter;
22: final String lineTerminator;
23: final ProgressListener pl;
24:
25: InplaceFileConverter(RuleSet ruleSet, ProgressListener pl) {
26: this .lineConverter = new LineConverter(ruleSet);
27: lineTerminator = System.getProperty("line.separator");
28: this .pl = pl;
29: }
30:
31: private byte[] readIntoByteArray(File file) throws IOException {
32: FileInputStream fis = new FileInputStream(file);
33: ByteArrayOutputStream baos = new ByteArrayOutputStream();
34: int n = 0;
35: byte[] buffer = new byte[BUFFER_LEN];
36: while ((n = fis.read(buffer)) != -1) {
37: // System.out.println("ba="+new String(buffer, "UTF-8"));
38: baos.write(buffer, 0, n);
39: }
40: fis.close();
41: return baos.toByteArray();
42: }
43:
44: void convert(File file) throws IOException {
45: byte[] originalBytes = readIntoByteArray(file);
46: byte[] convertedBytes = convertIntoTempByteArray(originalBytes);
47: if (lineConverter.atLeastOneMatchOccured()) {
48: //System.out.println("Converting ["+file+"]");
49: writeConvertedBytesIntoFile(file, convertedBytes);
50: pl.onInplaceConversion(file);
51: } else {
52: //System.out.println("Not touching ["+file+"]");
53: }
54: }
55:
56: private void writeConvertedBytesIntoFile(File file,
57: byte[] convertedBytes) throws IOException {
58: FileOutputStream fos = new FileOutputStream(file);
59: fos.write(convertedBytes);
60: fos.flush();
61: fos.close();
62: }
63:
64: private byte[] convertIntoTempByteArray(byte[] input)
65: throws IOException {
66: ByteArrayInputStream bais = new ByteArrayInputStream(input);
67: Reader reader = new InputStreamReader(bais);
68: BufferedReader breader = new BufferedReader(reader);
69: ByteArrayOutputStream baos = new ByteArrayOutputStream();
70: while (true) {
71: String line = breader.readLine();
72: if (line != null) {
73: String[] replacement = lineConverter
74: .getReplacement(line);
75: writeReplacement(baos, replacement);
76: } else {
77: break;
78: }
79: }
80: return baos.toByteArray();
81: }
82:
83: private void writeReplacement(OutputStream os, String[] replacement)
84: throws IOException {
85: for (int i = 0; i < replacement.length; i++) {
86: os.write(replacement[i].getBytes());
87: os.write(lineTerminator.getBytes());
88: }
89: }
90: }
|