001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.pattern;
015
016import java.util.List;
017import java.util.regex.Pattern;
018
019public class ReplacingCompositeConverter<E> extends CompositeConverter<E> {
020
021    Pattern pattern;
022    String regex;
023    String replacement;
024
025    public void start() {
026        final List<String> optionList = getOptionList();
027        if (optionList == null) {
028            addError("at least two options are expected whereas you have declared none");
029            return;
030        }
031
032        int numOpts = optionList.size();
033
034        if (numOpts < 2) {
035            addError("at least two options are expected whereas you have declared only " + numOpts + "as [" + optionList
036                    + "]");
037            return;
038        }
039        regex = optionList.get(0);
040        pattern = Pattern.compile(regex);
041        replacement = optionList.get(1);
042        super.start();
043    }
044
045    @Override
046    protected String transform(E event, String in) {
047        if (!started)
048            return in;
049        return pattern.matcher(in).replaceAll(replacement);
050    }
051}