001: /*
002: * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright
003: * notice. All rights reserved.
004: */
005: package com.tc.util;
006:
007: import java.io.BufferedOutputStream;
008: import java.io.BufferedReader;
009: import java.io.File;
010: import java.io.FileInputStream;
011: import java.io.FileNotFoundException;
012: import java.io.FileOutputStream;
013: import java.io.IOException;
014: import java.io.InputStreamReader;
015: import java.util.Arrays;
016: import java.util.Comparator;
017: import java.util.regex.Matcher;
018: import java.util.regex.Pattern;
019:
020: public final class ReplaceLine {
021:
022: private ReplaceLine() {
023: // cannot instantiate
024: }
025:
026: /**
027: * Replaces lines matching a token regular expression group.
028: *
029: * @return true if all tokens found matches
030: */
031: public static void parseFile(ReplaceLine.Token[] tokens, File file)
032: throws FileNotFoundException, IOException {
033: Arrays.sort(tokens, new Comparator() {
034: public int compare(Object o1, Object o2) {
035: return new Integer(((Token) o1).lineNumber)
036: .compareTo(new Integer(((Token) o2).lineNumber));
037: }
038: });
039:
040: int tokenIndex = 0, lineIndex = 0;
041: StringBuffer text = new StringBuffer();
042: BufferedReader reader = new BufferedReader(
043: new InputStreamReader(new FileInputStream(file)));
044:
045: try {
046: String line;
047: while ((line = reader.readLine()) != null) {
048: if (tokenIndex < tokens.length
049: && ++lineIndex == tokens[tokenIndex].lineNumber) {
050: line = replaceToken(
051: tokens[tokenIndex].replacePattern, line,
052: tokens[tokenIndex].value);
053: tokenIndex++;
054: }
055: text.append(line + "\n");
056: }
057: } finally {
058: try {
059: reader.close();
060: } catch (IOException ioe) {
061: // ignore
062: }
063: }
064:
065: BufferedOutputStream out = new BufferedOutputStream(
066: new FileOutputStream(file));
067:
068: try {
069: out.write(text.toString().getBytes());
070: out.flush();
071: } finally {
072: try {
073: out.close();
074: } catch (IOException ioe) {
075: // ignore
076: }
077: }
078: }
079:
080: private static String replaceToken(String expression, String text,
081: String value) {
082: Pattern pattern = Pattern.compile(expression);
083: Matcher matcher = pattern.matcher(text);
084: while (matcher.find()) {
085: return matcher.replaceAll(value);
086: }
087: return text;
088: }
089:
090: public static class Token {
091: private final int lineNumber;
092: private final String replacePattern;
093: private final String value;
094:
095: public Token(int lineNumber, String replacePattern, String value) {
096: this.lineNumber = lineNumber;
097: this.replacePattern = replacePattern;
098: this.value = value;
099: }
100: }
101: }
|