ReplacementTable.java

  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. import org.slf4j.Logger;
  23. import org.slf4j.LoggerFactory;

  24. import java.util.HashMap;
  25. import java.util.Iterator;
  26. import java.util.Map;

  27. /**
  28.  * Decorator that replaces configured values from the decorated table
  29.  * with replacement values.
  30.  *
  31.  * @author Manuel Laflamme
  32.  * @since Mar 17, 2003
  33.  * @version $Revision$
  34.  */
  35. public class ReplacementTable implements ITable
  36. {

  37.     /**
  38.      * Logger for this class
  39.      */
  40.     private static final Logger logger = LoggerFactory.getLogger(ReplacementTable.class);

  41.     private final ITable _table;
  42.     private final Map _objectMap;
  43.     private final Map _substringMap;
  44.     private String _startDelim;
  45.     private String _endDelim;
  46.     private boolean _strictReplacement;

  47.     /**
  48.      * Create a new ReplacementTable object that decorates the specified table.
  49.      *
  50.      * @param table the decorated table
  51.      */
  52.     public ReplacementTable(ITable table)
  53.     {
  54.         this(table, new HashMap(), new HashMap(), null, null);
  55.     }

  56.     public ReplacementTable(ITable table, Map objectMap, Map substringMap,
  57.             String startDelimiter, String endDelimiter)
  58.     {
  59.         _table = table;
  60.         _objectMap = objectMap;
  61.         _substringMap = substringMap;
  62.         _startDelim = startDelimiter;
  63.         _endDelim = endDelimiter;
  64.     }

  65.     /**
  66.      * Setting this property to true indicates that when no replacement
  67.      * is found for a delimited substring the replacement will fail fast.
  68.      *
  69.      * @param strictReplacement true if replacement should be strict
  70.      */
  71.     public void setStrictReplacement(boolean strictReplacement)
  72.     {
  73.         if(logger.isDebugEnabled())
  74.             logger.debug("setStrictReplacement(strictReplacement={}) - start", strictReplacement);
  75.        
  76.         this._strictReplacement = strictReplacement;
  77.     }
  78.    
  79.     /**
  80.      * Add a new Object replacement mapping.
  81.      *
  82.      * @param originalObject the object to replace
  83.      * @param replacementObject the replacement object
  84.      */
  85.     public void addReplacementObject(Object originalObject, Object replacementObject)
  86.     {
  87.         logger.debug("addReplacementObject(originalObject={}, replacementObject={}) - start", originalObject, replacementObject);

  88.         _objectMap.put(originalObject, replacementObject);
  89.     }

  90.     /**
  91.      * Add a new substring replacement mapping.
  92.      *
  93.      * @param originalSubstring the substring to replace
  94.      * @param replacementSubstring the replacement substring
  95.      */
  96.     public void addReplacementSubstring(String originalSubstring,
  97.             String replacementSubstring)
  98.     {
  99.         logger.debug("addReplacementSubstring(originalSubstring={}, replacementSubstring={}) - start", originalSubstring, replacementSubstring);

  100.         if (originalSubstring == null || replacementSubstring == null)
  101.         {
  102.             throw new NullPointerException();
  103.         }

  104.         _substringMap.put(originalSubstring, replacementSubstring);
  105.     }

  106.     /**
  107.      * Sets substring delimiters.
  108.      */
  109.     public void setSubstringDelimiters(String startDelimiter, String endDelimiter)
  110.     {
  111.         logger.debug("setSubstringDelimiters(startDelimiter={}, endDelimiter={}) - start", startDelimiter, endDelimiter);

  112.         if (startDelimiter == null || endDelimiter == null)
  113.         {
  114.             throw new NullPointerException();
  115.         }

  116.         _startDelim = startDelimiter;
  117.         _endDelim = endDelimiter;
  118.     }

  119.     /**
  120.      * Replace occurrences of source in text with target. Operates directly on text.
  121.      */
  122.     private void replaceAll(StringBuilder text, String source, String target) {
  123.         int index = 0;
  124.         while((index = text.toString().indexOf(source, index)) != -1)
  125.         {
  126.             text.replace(index, index+source.length(), target);
  127.             index += target.length();
  128.         }
  129.     }
  130.    
  131.     private String replaceStrings(String value, String lDelim, String rDelim) {
  132.         final StringBuilder buffer = new StringBuilder(value);

  133.         for (Iterator it = _substringMap.entrySet().iterator(); it.hasNext();)
  134.         {
  135.             Map.Entry entry = (Map.Entry)it.next();
  136.             String original = (String)entry.getKey();
  137.             String replacement = (String)entry.getValue();
  138.             replaceAll(buffer, lDelim + original + rDelim, replacement);
  139.         }

  140.         return buffer == null ? value : buffer.toString();        
  141.     }
  142.    
  143.     private String replaceSubstrings(String value)
  144.     {
  145.         return replaceStrings(value, "", "");
  146.     }    

  147.     /**
  148.      * @throws DataSetException when stringReplacement fails
  149.      */
  150.     private String replaceDelimitedSubstrings(String value) throws DataSetException
  151.     {
  152.         StringBuilder buffer = null;

  153.         int startIndex = 0;
  154.         int endIndex = 0;
  155.         int lastEndIndex = 0;
  156.         for(;;)
  157.         {
  158.             startIndex = value.indexOf(_startDelim, lastEndIndex);
  159.             if (startIndex != -1)
  160.             {
  161.                 endIndex = value.indexOf(_endDelim, startIndex + _startDelim.length());
  162.                 if (endIndex != -1)
  163.                 {
  164.                     if (buffer == null)
  165.                     {
  166.                         buffer = new StringBuilder();
  167.                     }

  168.                     String substring = value.substring(
  169.                             startIndex + _startDelim.length(), endIndex);
  170.                     if (_substringMap.containsKey(substring))
  171.                     {
  172.                         buffer.append(value.substring(lastEndIndex, startIndex));
  173.                         buffer.append(_substringMap.get(substring));
  174.                     }
  175.                     else if (_strictReplacement)
  176.                     {
  177.                         throw new DataSetException(
  178.                                 "Strict Replacement was set to true, but no"
  179.                                 + " replacement was found for substring '"
  180.                                 + substring + "' in the value '" + value + "'");
  181.                     }
  182.                     else
  183.                     {
  184.                         logger.debug("Did not find a replacement map entry for substring={}. " +
  185.                                 "Leaving original value there.", substring);
  186.                         buffer.append(value.substring(
  187.                                 lastEndIndex, endIndex + _endDelim.length()));
  188.                     }

  189.                     lastEndIndex = endIndex + _endDelim.length();
  190.                 }
  191.             }

  192.             // No more delimited substring
  193.             if (startIndex == -1 || endIndex == -1)
  194.             {
  195.                 if (buffer != null)
  196.                 {
  197.                     buffer.append(value.substring(lastEndIndex));
  198.                 }
  199.                 break;
  200.             }
  201.         }

  202.         return buffer == null ? value : buffer.toString();
  203.     }

  204.     ////////////////////////////////////////////////////////////////////////
  205.     // ITable interface

  206.     public ITableMetaData getTableMetaData()
  207.     {
  208.         return _table.getTableMetaData();
  209.     }

  210.     public int getRowCount()
  211.     {
  212.         return _table.getRowCount();
  213.     }

  214.     public Object getValue(int row, String column) throws DataSetException
  215.     {
  216.         if(logger.isDebugEnabled())
  217.             logger.debug("getValue(row={}, columnName={}) - start", row, column);

  218.         Object value = _table.getValue(row, column);

  219.         // Object replacement
  220.         if (_objectMap.containsKey(value))
  221.         {
  222.             return _objectMap.get(value);
  223.         }

  224.         // Stop here if substring replacement not applicable
  225.         if (_substringMap.size() == 0 || !(value instanceof String))
  226.         {
  227.             return value;
  228.         }

  229.         // Substring replacement
  230.         if (_startDelim != null && _endDelim != null)
  231.         {
  232.             return replaceDelimitedSubstrings((String)value);
  233.         }
  234.         return replaceSubstrings((String)value);
  235.     }
  236.    
  237.    
  238.     public String toString()
  239.     {
  240.         final StringBuilder sb = new StringBuilder();
  241.         sb.append(getClass().getName()).append("[");
  242.         sb.append("_strictReplacement=").append(_strictReplacement);
  243.         sb.append(", _table=").append(_table);
  244.         sb.append(", _objectMap=").append(_objectMap);
  245.         sb.append(", _substringMap=").append(_substringMap);
  246.         sb.append(", _startDelim=").append(_startDelim);
  247.         sb.append(", _endDelim=").append(_endDelim);
  248.         sb.append("]");
  249.         return sb.toString();
  250.     }
  251. }