01: package org.slf4j.migrator.line;
02:
03: import java.util.Arrays;
04: import java.util.Iterator;
05: import java.util.regex.Matcher;
06: import java.util.regex.Pattern;
07:
08: public class LineConverter {
09:
10: final RuleSet ruleSet;
11: boolean atLeastOneMatchOccured = false;
12:
13: public LineConverter(RuleSet ruleSet) {
14: this .ruleSet = ruleSet;
15: }
16:
17: /**
18: * Check if the specified text is matching some conversions rules.
19: * If a rule matches, ask for line replacement.
20: *
21: * <p>In case no rule can be applied, then the input text is
22: * returned without change.
23: *
24: * @param text
25: * @return String
26: */
27: public String[] getReplacement(String text) {
28: ConversionRule conversionRule;
29: Pattern pattern;
30: Matcher matcher;
31: Iterator<ConversionRule> conversionRuleIterator = ruleSet
32: .iterator();
33: String additionalLine = null;
34: while (conversionRuleIterator.hasNext()) {
35: conversionRule = conversionRuleIterator.next();
36: pattern = conversionRule.getPattern();
37: matcher = pattern.matcher(text);
38: if (matcher.find()) {
39: // System.out.println("matching " + text);
40: atLeastOneMatchOccured = true;
41: String replacementText = conversionRule
42: .replace(matcher);
43: text = matcher.replaceAll(replacementText);
44: if (conversionRule.getAdditionalLine() != null) {
45: additionalLine = conversionRule.getAdditionalLine();
46: }
47: }
48: }
49:
50: if (additionalLine == null) {
51: return new String[] { text };
52: } else {
53: return new String[] { text, additionalLine };
54: }
55: }
56:
57: public String getOneLineReplacement(String text) {
58: String[] r = getReplacement(text);
59: if (r.length != 1) {
60: throw new IllegalStateException(
61: "Expecting a single string but got "
62: + Arrays.toString(r));
63: } else {
64: return r[0];
65: }
66: }
67:
68: public boolean atLeastOneMatchOccured() {
69: return atLeastOneMatchOccured;
70: }
71: }
|