1   package org.slf4j.migrator.line;
2   
3   import java.util.Arrays;
4   import java.util.Iterator;
5   import java.util.regex.Matcher;
6   import java.util.regex.Pattern;
7   
8   
9   public class LineConverter {
10  
11    final RuleSet ruleSet;
12    boolean atLeastOneMatchOccured = false;
13    
14    public LineConverter(RuleSet ruleSet) {
15      this.ruleSet = ruleSet;
16    }
17  
18    /**
19     * Check if the specified text is matching some conversions rules. 
20     * If a rule matches, ask for line replacement.
21     * 
22     * <p>In case no rule can be applied, then the input text is
23     * returned without change.
24     * 
25     * @param text
26     * @return String
27     */
28    public String[] getReplacement(String text) {
29      ConversionRule conversionRule;
30      Pattern pattern;
31      Matcher matcher;
32      Iterator<ConversionRule> conversionRuleIterator = ruleSet.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.replace(matcher);
42          text = matcher.replaceAll(replacementText);
43          if(conversionRule.getAdditionalLine() != null) {
44            additionalLine = conversionRule.getAdditionalLine();
45          }
46        }
47      }
48      
49      if(additionalLine == null) {
50        return new String[] {text};
51      } else {
52        return new String[] {text, additionalLine};
53      }
54    }
55  
56    public String getOneLineReplacement(String text) {
57      String[] r = getReplacement(text);
58      if(r.length != 1) {
59        throw new IllegalStateException("Expecting a single string but got "+Arrays.toString(r));
60      } else {
61        return r[0];
62      }
63    }
64    public boolean atLeastOneMatchOccured() {
65      return atLeastOneMatchOccured;
66    }
67  }