View Javadoc
1   /*
2    *
3    * The DbUnit Database Testing Framework
4    * Copyright (C)2002-2004, DbUnit.org
5    *
6    * This library is free software; you can redistribute it and/or
7    * modify it under the terms of the GNU Lesser General Public
8    * License as published by the Free Software Foundation; either
9    * version 2.1 of the License, or (at your option) any later version.
10   *
11   * This library is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   * Lesser General Public License for more details.
15   *
16   * You should have received a copy of the GNU Lesser General Public
17   * License along with this library; if not, write to the Free Software
18   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   *
20   */
21  package org.dbunit.dataset;
22  
23  import org.slf4j.Logger;
24  import org.slf4j.LoggerFactory;
25  
26  import java.util.HashMap;
27  import java.util.Iterator;
28  import java.util.Map;
29  
30  /**
31   * Decorator that replaces configured values from the decorated table
32   * with replacement values.
33   *
34   * @author Manuel Laflamme
35   * @since Mar 17, 2003
36   * @version $Revision$
37   */
38  public class ReplacementTable implements ITable
39  {
40  
41      /**
42       * Logger for this class
43       */
44      private static final Logger logger = LoggerFactory.getLogger(ReplacementTable.class);
45  
46      private final ITable _table;
47      private final Map _objectMap;
48      private final Map _substringMap;
49      private String _startDelim;
50      private String _endDelim;
51      private boolean _strictReplacement;
52  
53      /**
54       * Create a new ReplacementTable object that decorates the specified table.
55       *
56       * @param table the decorated table
57       */
58      public ReplacementTable(ITable table)
59      {
60          this(table, new HashMap(), new HashMap(), null, null);
61      }
62  
63      public ReplacementTable(ITable table, Map objectMap, Map substringMap,
64              String startDelimiter, String endDelimiter)
65      {
66          _table = table;
67          _objectMap = objectMap;
68          _substringMap = substringMap;
69          _startDelim = startDelimiter;
70          _endDelim = endDelimiter;
71      }
72  
73      /**
74       * Setting this property to true indicates that when no replacement
75       * is found for a delimited substring the replacement will fail fast.
76       * 
77       * @param strictReplacement true if replacement should be strict
78       */
79      public void setStrictReplacement(boolean strictReplacement) 
80      {
81      	if(logger.isDebugEnabled())
82      		logger.debug("setStrictReplacement(strictReplacement={}) - start", String.valueOf(strictReplacement));
83      	
84          this._strictReplacement = strictReplacement;
85      }
86      
87      /**
88       * Add a new Object replacement mapping.
89       *
90       * @param originalObject the object to replace
91       * @param replacementObject the replacement object
92       */
93      public void addReplacementObject(Object originalObject, Object replacementObject)
94      {
95          logger.debug("addReplacementObject(originalObject={}, replacementObject={}) - start", originalObject, replacementObject);
96  
97          _objectMap.put(originalObject, replacementObject);
98      }
99  
100     /**
101      * Add a new substring replacement mapping.
102      *
103      * @param originalSubstring the substring to replace
104      * @param replacementSubstring the replacement substring
105      */
106     public void addReplacementSubstring(String originalSubstring,
107             String replacementSubstring)
108     {
109         logger.debug("addReplacementSubstring(originalSubstring={}, replacementSubstring={}) - start", originalSubstring, replacementSubstring);
110 
111         if (originalSubstring == null || replacementSubstring == null)
112         {
113             throw new NullPointerException();
114         }
115 
116         _substringMap.put(originalSubstring, replacementSubstring);
117     }
118 
119     /**
120      * Sets substring delimiters.
121      */
122     public void setSubstringDelimiters(String startDelimiter, String endDelimiter)
123     {
124         logger.debug("setSubstringDelimiters(startDelimiter={}, endDelimiter={}) - start", startDelimiter, endDelimiter);
125 
126         if (startDelimiter == null || endDelimiter == null)
127         {
128             throw new NullPointerException();
129         }
130 
131         _startDelim = startDelimiter;
132         _endDelim = endDelimiter;
133     }
134 
135     /**
136      * Replace occurrences of source in text with target. Operates directly on text.
137      */
138     private void replaceAll(StringBuffer text, String source, String target) {
139         int index = 0;
140         while((index = text.toString().indexOf(source, index)) != -1)
141         {
142             text.replace(index, index+source.length(), target);
143             index += target.length();
144         }
145     }
146     
147     private String replaceStrings(String value, String lDelim, String rDelim) {
148         StringBuffer buffer = new StringBuffer(value);
149 
150         for (Iterator it = _substringMap.entrySet().iterator(); it.hasNext();)
151         {
152             Map.Entry entry = (Map.Entry)it.next();
153             String original = (String)entry.getKey();
154             String replacement = (String)entry.getValue();
155             replaceAll(buffer, lDelim + original + rDelim, replacement);
156         }
157 
158         return buffer == null ? value : buffer.toString();        
159     }
160     
161     private String replaceSubstrings(String value)
162     {
163         return replaceStrings(value, "", "");
164     }    
165 
166     /**
167      * @throws DataSetException when stringReplacement fails
168      */
169     private String replaceDelimitedSubstrings(String value) throws DataSetException
170     {
171         StringBuffer buffer = null;
172 
173         int startIndex = 0;
174         int endIndex = 0;
175         int lastEndIndex = 0;
176         for(;;)
177         {
178             startIndex = value.indexOf(_startDelim, lastEndIndex);
179             if (startIndex != -1)
180             {
181                 endIndex = value.indexOf(_endDelim, startIndex + _startDelim.length());
182                 if (endIndex != -1)
183                 {
184                     if (buffer == null)
185                     {
186                         buffer = new StringBuffer();
187                     }
188 
189                     String substring = value.substring(
190                             startIndex + _startDelim.length(), endIndex);
191                     if (_substringMap.containsKey(substring))
192                     {
193                         buffer.append(value.substring(lastEndIndex, startIndex));
194                         buffer.append(_substringMap.get(substring));
195                     }
196                     else if (_strictReplacement)
197                     {
198                         throw new DataSetException(
199                                 "Strict Replacement was set to true, but no"
200                                 + " replacement was found for substring '" 
201                                 + substring + "' in the value '" + value + "'");
202                     }
203                     else
204                     {
205                         logger.debug("Did not find a replacement map entry for substring={}. " +
206                         		"Leaving original value there.", substring);
207                         buffer.append(value.substring(
208                                 lastEndIndex, endIndex + _endDelim.length()));
209                     }
210 
211                     lastEndIndex = endIndex + _endDelim.length();
212                 }
213             }
214 
215             // No more delimited substring
216             if (startIndex == -1 || endIndex == -1)
217             {
218                 if (buffer != null)
219                 {
220                     buffer.append(value.substring(lastEndIndex));
221                 }
222                 break;
223             }
224         }
225 
226         return buffer == null ? value : buffer.toString();
227     }
228 
229     ////////////////////////////////////////////////////////////////////////
230     // ITable interface
231 
232     public ITableMetaData getTableMetaData()
233     {
234         return _table.getTableMetaData();
235     }
236 
237     public int getRowCount()
238     {
239         return _table.getRowCount();
240     }
241 
242     public Object getValue(int row, String column) throws DataSetException
243     {
244         if(logger.isDebugEnabled())
245             logger.debug("getValue(row={}, columnName={}) - start", Integer.toString(row), column);
246 
247         Object value = _table.getValue(row, column);
248 
249         // Object replacement
250         if (_objectMap.containsKey(value))
251         {
252             return _objectMap.get(value);
253         }
254 
255         // Stop here if substring replacement not applicable
256         if (_substringMap.size() == 0 || !(value instanceof String))
257         {
258             return value;
259         }
260 
261         // Substring replacement
262         if (_startDelim != null && _endDelim != null)
263         {
264             return replaceDelimitedSubstrings((String)value);
265         }
266         return replaceSubstrings((String)value);
267     }
268     
269     
270     public String toString()
271     {
272     	StringBuffer sb = new StringBuffer();
273     	sb.append(getClass().getName()).append("[");
274     	sb.append("_strictReplacement=").append(_strictReplacement);
275     	sb.append(", _table=").append(_table);
276     	sb.append(", _objectMap=").append(_objectMap);
277     	sb.append(", _substringMap=").append(_substringMap);
278     	sb.append(", _startDelim=").append(_startDelim);
279     	sb.append(", _endDelim=").append(_endDelim);
280     	sb.append("]");
281     	return sb.toString();
282     }
283 }