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.ArrayList; 013import java.util.List; 014import java.util.Map; 015import java.util.regex.Matcher; 016import java.util.regex.Pattern; 017 018import org.kew.rmf.utils.Dictionary; 019 020/** 021 * Uses a {@link org.kew.rmf.utils.Dictionary} object of which it iterates over 022 * the keys to use each as a regular expression; if the pattern matches, it 023 * transforms the string accordingly returning the corresponding value of the 024 * Dictionary. 025 * <br/> 026 * If multiTransform is set it goes through the whole list of keys in the 027 * same way, otherwise it returns after the first match. 028 */ 029public class DictionaryRegexTransformer implements Transformer { 030 031 private Dictionary dictionary; 032 private boolean multiTransform = false; 033 034 private List<Pattern> patterns = new ArrayList<>(); 035 private List<String> replacements = new ArrayList<>(); 036 037 @Override 038 public String transform(String s) throws TransformationException { 039 for (int i = 0; i < patterns.size(); i++) { 040 Pattern p = patterns.get(i); 041 String r = replacements.get(i); 042 043 Matcher m = p.matcher(s); 044 if (m.find()) { 045 s = m.replaceAll(r); 046 if (this.multiTransform == false) return s; 047 } 048 } 049 return s; 050 } 051 052 public Dictionary getDictionary() { 053 return dictionary; 054 } 055 public void setDictionary(Dictionary dictionary) { 056 this.dictionary = dictionary; 057 058 for (Map.Entry<String, String> entry : this.dictionary.entrySet()) { 059 Pattern p = Pattern.compile(entry.getKey()); 060 patterns.add(p); 061 replacements.add(entry.getValue()); 062 } 063 } 064 065 public boolean isMultiTransform() { 066 return multiTransform; 067 } 068 public void setMultiTransform(boolean multiTransform) { 069 this.multiTransform = multiTransform; 070 } 071}