001/*
002 * Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
003 *
004 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
005 *
006 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
007 *
008 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
009 */
010package org.kew.rmf.transformers;
011
012import java.util.Map;
013import java.util.regex.Matcher;
014import java.util.regex.Pattern;
015
016import org.kew.rmf.utils.Dictionary;
017
018/**
019 * Uses a {@link org.kew.rmf.utils.Dictionary} object of which it iterates over
020 * the keys to use each as a regular expression; if the pattern matches, it
021 * transforms the string accordingly returning the corresponding value of the
022 * Dictionary.
023 *
024 * If multiTransform is set it goes through the whole list of keys in the
025 * same way, otherwise it returns after the first match.
026 */
027public class DictionaryRegexTransformer implements Transformer {
028
029    private Dictionary dictionary;
030    private boolean multiTransform = false;
031
032    @Override
033    public String transform(String s) throws TransformationException {
034        for (Map.Entry<String, String> entry : this.dictionary.entrySet()) {
035            Pattern p = Pattern.compile(entry.getKey());
036            Matcher m = p.matcher(s);
037            if (m.find()) {
038                s = m.replaceAll(entry.getValue());
039                if (this.multiTransform == false) return s;
040            }
041        }
042        return s;
043    }
044
045    public Dictionary getDictionary() {
046        return dictionary;
047    }
048    public void setDictionary(Dictionary dictionary) {
049        this.dictionary = dictionary;
050    }
051
052    public boolean isMultiTransform() {
053        return multiTransform;
054    }
055    public void setMultiTransform(boolean multiTransform) {
056        this.multiTransform = multiTransform;
057    }
058}