View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.pattern;
15  
16  import java.util.List;
17  import java.util.regex.Pattern;
18  
19  public class ReplacingCompositeConverter<E> extends CompositeConverter<E> {
20  
21    Pattern pattern;
22    String regex;
23    String replacement;
24  
25    public void start() {
26      final List<String> optionList = getOptionList();
27      if (optionList == null) {
28        addError("at least two options are expected whereas you have declared none");
29        return;
30      }
31  
32      int numOpts = optionList.size();
33  
34      if (numOpts < 2) {
35        addError("at least two options are expected whereas you have declared only " + numOpts + "as [" + optionList + "]");
36        return;
37      }
38      regex = optionList.get(0);
39      pattern = Pattern.compile(regex);
40      replacement = optionList.get(1);
41      super.start();
42    }
43  
44    @Override
45    String transform(String in) {
46      if (!started)
47        return in;
48      return pattern.matcher(in).replaceAll(replacement);
49    }
50  }