Coverage Report - org.jbehave.core.model.ExamplesTable
 
Classes in this File Line Coverage Branch Coverage Complexity
ExamplesTable
99%
142/143
98%
55/56
1.941
ExamplesTable$RowNotFound
100%
2/2
N/A
1.941
 
 1  
 package org.jbehave.core.model;
 2  
 
 3  
 import java.io.ByteArrayInputStream;
 4  
 import java.io.IOException;
 5  
 import java.io.PrintStream;
 6  
 import java.util.ArrayList;
 7  
 import java.util.Collections;
 8  
 import java.util.HashMap;
 9  
 import java.util.LinkedHashMap;
 10  
 import java.util.List;
 11  
 import java.util.Map;
 12  
 import java.util.Properties;
 13  
 import java.util.regex.Matcher;
 14  
 import java.util.regex.Pattern;
 15  
 
 16  
 import org.apache.commons.lang.StringUtils;
 17  
 import org.apache.commons.lang.builder.ToStringBuilder;
 18  
 import org.apache.commons.lang.builder.ToStringStyle;
 19  
 import org.jbehave.core.steps.ChainedRow;
 20  
 import org.jbehave.core.steps.ConvertedParameters;
 21  
 import org.jbehave.core.steps.ParameterConverters;
 22  
 import org.jbehave.core.steps.Parameters;
 23  
 import org.jbehave.core.steps.Row;
 24  
 
 25  
 import static java.lang.Boolean.parseBoolean;
 26  
 import static java.util.regex.Pattern.DOTALL;
 27  
 import static java.util.regex.Pattern.compile;
 28  
 
 29  
 /**
 30  
  * <p>
 31  
  * Represents a tabular structure that holds rows of example data for parameters
 32  
  * named via the column headers:
 33  
  * <p/>
 34  
  * 
 35  
  * <pre>
 36  
  * |header 1|header 2| .... |header n|
 37  
  * |value 11|value 12| .... |value 1n|
 38  
  * ...
 39  
  * |value m1|value m2| .... |value mn|
 40  
  * </pre>
 41  
  * <p>
 42  
  * Different header and value column separators can be specified to replace the
 43  
  * default separator "|":
 44  
  * </p>
 45  
  * 
 46  
  * <pre>
 47  
  * !!header 1!!header 2!! .... !!header n!!
 48  
  * !value 11!value 12! .... !value 1n!
 49  
  * ...
 50  
  * !value m1!value m2| .... !value mn!
 51  
  * </pre>
 52  
  * <p>
 53  
  * Rows starting with an ignorable separator are allowed and ignored:
 54  
  * </p>
 55  
  * 
 56  
  * <pre>
 57  
  * |header 1|header 2| .... |header n|
 58  
  * |-- A commented row --|
 59  
  * |value 11|value 12| .... |value 1n|
 60  
  * ...
 61  
  * |-- Another commented row --|
 62  
  * |value m1|value m2| .... |value mn|
 63  
  * </pre>
 64  
  * <p>
 65  
  * Ignorable separator is configurable and defaults to "|--".
 66  
  * </p>
 67  
  * <p>
 68  
  * The separators are also configurable via inlined properties: 
 69  
  * <pre>
 70  
  * {ignorableSeparator=!--,headerSeparator=!,valueSeparator=!}
 71  
  * !header 1!header 2! .... !header n!
 72  
  * !-- A commented row --!
 73  
  * !value 11!value 12! .... !value 1n!
 74  
  * ...
 75  
  * !-- Another commented row --!
 76  
  * !value m1!value m2! .... !value mn!
 77  
  * </pre>
 78  
  * 
 79  
  * </p>
 80  
  * <p>
 81  
  * By default all column values are trimmed. To avoid trimming the values:
 82  
  * 
 83  
  * <pre>
 84  
  * {trim=false}
 85  
  * | header 1 | header 2 | .... | header n |
 86  
  * | value 11 | value 12 | .... | value 1n |
 87  
  * </pre>
 88  
  * 
 89  
  * </p>
 90  
  * 
 91  
  * <p>
 92  
  * The table also allows the retrieval of row values as converted parameters.
 93  
  * Use {@link #getRowAsParameters(int)} and invoke
 94  
  * {@link Parameters#valueAs(String, Class)} specifying the header and the class
 95  
  * type of the parameter.
 96  
  * </p>
 97  
  * 
 98  
  * <p>
 99  
  * Once created, the table row can be modified, via the
 100  
  * {@link #withRowValues(int, Map)} method, by specifying the map of row values
 101  
  * to be changed.
 102  
  * </p>
 103  
  * 
 104  
  * <p>
 105  
  * A table can also be created by providing the entire data content, via the
 106  
  * {@link #withRows(List<Map<String,String>>)} method.
 107  
  * 
 108  
  * </p>
 109  
  * The parsing code assumes that the number of columns for data rows is the same
 110  
  * as in the header, if a row has less fields, the remaining are filled with
 111  
  * empty values, if it has more, the fields are ignored.
 112  
  * <p>
 113  
  */
 114  
 public class ExamplesTable {
 115  1
     private static final Map<String, String> EMPTY_MAP = Collections.emptyMap();
 116  
     private static final String EMPTY_VALUE = "";
 117  
 
 118  1
     public static final ExamplesTable EMPTY = new ExamplesTable("");
 119  
 
 120  
     private static final String ROW_SEPARATOR = "\n";
 121  
     private static final String HEADER_SEPARATOR = "|";
 122  
     private static final String VALUE_SEPARATOR = "|";
 123  
     private static final String IGNORABLE_SEPARATOR = "|--";
 124  
 
 125  177
     private final List<Map<String, String>> data = new ArrayList<Map<String, String>>();
 126  
     private final String tableAsString;
 127  
     private final String headerSeparator;
 128  
     private final String valueSeparator;
 129  
     private final String ignorableSeparator;
 130  
     private final ParameterConverters parameterConverters;
 131  177
     private final List<String> headers = new ArrayList<String>();
 132  177
     private final Properties properties = new Properties();
 133  177
     private Map<String, String> namedParameters = new HashMap<String, String>();
 134  177
     private boolean trim = true;
 135  
 
 136  
     private final Row defaults;
 137  
 
 138  
     public ExamplesTable(String tableAsString) {
 139  37
         this(tableAsString, HEADER_SEPARATOR, VALUE_SEPARATOR);
 140  37
     }
 141  
 
 142  
     public ExamplesTable(String tableAsString, String headerSeparator, String valueSeparator) {
 143  39
         this(tableAsString, headerSeparator, valueSeparator, IGNORABLE_SEPARATOR, new ParameterConverters());
 144  39
     }
 145  
 
 146  
     public ExamplesTable(String tableAsString, String headerSeparator, String valueSeparator,
 147  176
             String ignorableSeparator, ParameterConverters parameterConverters) {
 148  176
         this.tableAsString = tableAsString;
 149  176
         this.headerSeparator = headerSeparator;
 150  176
         this.valueSeparator = valueSeparator;
 151  176
         this.ignorableSeparator = ignorableSeparator;
 152  176
         this.parameterConverters = parameterConverters;
 153  176
         this.defaults = new ConvertedParameters(EMPTY_MAP, parameterConverters);
 154  176
         parse(tableAsString);
 155  176
     }
 156  
 
 157  1
     private ExamplesTable(ExamplesTable other, Row defaults) {
 158  1
         this.data.addAll(other.data);
 159  1
         this.tableAsString = other.tableAsString;
 160  1
         this.headerSeparator = other.headerSeparator;
 161  1
         this.valueSeparator = other.valueSeparator;
 162  1
         this.ignorableSeparator = other.ignorableSeparator;
 163  1
         this.parameterConverters = other.parameterConverters;
 164  1
         this.headers.addAll(other.headers);
 165  1
         this.properties.putAll(other.properties);
 166  1
         this.defaults = defaults;
 167  1
     }
 168  
 
 169  
     private void parse(String tableAsString) {
 170  176
         data.clear();
 171  176
         headers.clear();
 172  176
         String[] rows = splitInRows(stripProperties(tableAsString.trim()));
 173  2449
         for (int row = 0; row < rows.length; row++) {
 174  2273
             String rowAsString = rows[row];
 175  2273
             if (rowAsString.startsWith(properties.getProperty("ignorableSeparator", ignorableSeparator)) || rowAsString.length()==0) {
 176  
                 // skip empty lines and rows that start with ignorable separator
 177  125
                 continue;
 178  2144
             } else if (row == 0) {
 179  52
                 List<String> columns = columnsFor(rowAsString, properties.getProperty("headerSeparator", headerSeparator));
 180  52
                 headers.addAll(columns);
 181  52
             } else {
 182  2092
                 List<String> columns = columnsFor(rowAsString, properties.getProperty("valueSeparator", valueSeparator));
 183  2092
                 Map<String, String> map = createRowMap();
 184  22281
                 for (int column = 0; column < columns.size(); column++) {
 185  20189
                     if(column<headers.size()) {
 186  20188
                         map.put(headers.get(column), columns.get(column));
 187  
                     }
 188  
                 }
 189  2092
                 data.add(map);
 190  
             }
 191  
         }
 192  176
     }
 193  
 
 194  
     private String stripProperties(String tableAsString) {
 195  176
         Pattern pattern = compile("\\{(.*?)\\}\\s*(.*)", DOTALL);
 196  176
         Matcher matcher = pattern.matcher(tableAsString);
 197  176
         if (matcher.matches()) {
 198  2
             parseProperties(matcher.group(1));
 199  2
             return matcher.group(2);
 200  
         }
 201  174
         return tableAsString;
 202  
     }
 203  
 
 204  
     private void parseProperties(String propertiesAsString) {
 205  2
         properties.clear();
 206  
         try {
 207  2
             properties.load(new ByteArrayInputStream(propertiesAsString.replace(",", ROW_SEPARATOR).getBytes()));
 208  0
         } catch (IOException e) {
 209  
             // carry on
 210  2
         }
 211  2
         trim = parseBoolean(properties.getProperty("trim", "true"));
 212  2
     }
 213  
 
 214  
     private String[] splitInRows(String table) {
 215  176
         return table.split(ROW_SEPARATOR);
 216  
     }
 217  
 
 218  
     private List<String> columnsFor(String row, String separator) {
 219  2144
         List<String> columns = new ArrayList<String>();
 220  
         // use split limit -1 to ensure that empty strings will not be discarded
 221  26723
         for (String column : row.split(buildRegex(separator), -1)) {
 222  24579
             columns.add(valueOf(column));
 223  
         }
 224  
         // there may be a leading and a trailing empty column which we ignore
 225  2144
         if (StringUtils.isBlank(columns.get(0))) {
 226  2138
             columns.remove(0);
 227  
         }
 228  2144
         int lastIndex = columns.size() - 1;
 229  2144
         if (lastIndex != -1 && StringUtils.isBlank(columns.get(lastIndex))) {
 230  2138
             columns.remove(lastIndex);
 231  
         }
 232  2144
         return columns;
 233  
     }
 234  
 
 235  
     private String valueOf(String column) {
 236  24579
         return trim ? column.trim() : column;
 237  
     }
 238  
 
 239  
     private String buildRegex(String separator) {
 240  2144
         char[] chars = separator.toCharArray();
 241  2144
         StringBuffer sb = new StringBuffer();
 242  4290
         for (char c : chars) {
 243  2146
             sb.append("\\").append(c);
 244  
         }
 245  2144
         return sb.toString();
 246  
     }
 247  
 
 248  
     protected Map<String, String> createRowMap() {
 249  2092
         return new LinkedHashMap<String, String>();
 250  
     }
 251  
 
 252  
     public ExamplesTable withDefaults(Parameters defaults) {
 253  1
         return new ExamplesTable(this, new ChainedRow(defaults, this.defaults));
 254  
     }
 255  
 
 256  
     public ExamplesTable withNamedParameters(Map<String, String> namedParameters) {
 257  1
         this.namedParameters = namedParameters;
 258  1
         return this;
 259  
     }
 260  
 
 261  
     public ExamplesTable withRowValues(int row, Map<String, String> values) {
 262  2
         getRow(row).putAll(values);
 263  2
         for (String header : values.keySet()) {
 264  3
             if (!headers.contains(header)) {
 265  1
                 headers.add(header);
 266  
             }
 267  
         }
 268  2
         return this;
 269  
     }
 270  
 
 271  
     public ExamplesTable withRows(List<Map<String, String>> values) {
 272  1
         this.data.clear();
 273  1
         this.data.addAll(values);
 274  1
         this.headers.clear();
 275  1
         this.headers.addAll(values.get(0).keySet());
 276  1
         return this;
 277  
     }
 278  
 
 279  
     public Properties getProperties() {
 280  2
         return properties;
 281  
     }
 282  
 
 283  
     public List<String> getHeaders() {
 284  25
         return headers;
 285  
     }
 286  
 
 287  
     public Map<String, String> getRow(int row) {
 288  208
         if (row > data.size() - 1) {
 289  1
             throw new RowNotFound(row);
 290  
         }
 291  207
         Map<String, String> values = data.get(row);
 292  207
         if (headers.size() != values.keySet().size()) {
 293  2
             for (String header : headers) {
 294  5
                 if (!values.containsKey(header)) {
 295  2
                     values.put(header, EMPTY_VALUE);
 296  
                 }
 297  
             }
 298  
         }
 299  207
         return values;
 300  
     }
 301  
 
 302  
     public Parameters getRowAsParameters(int row) {
 303  9
         return getRowAsParameters(row, false);
 304  
     }
 305  
 
 306  
     public Parameters getRowAsParameters(int row, boolean replaceNamedParameters) {
 307  13
         Map<String, String> rowValues = getRow(row);
 308  12
         return createParameters((replaceNamedParameters ? replaceNamedParameters(rowValues) : rowValues));
 309  
     }
 310  
 
 311  
     private Map<String, String> replaceNamedParameters(Map<String, String> row) {
 312  1
         Map<String, String> replaced = new HashMap<String, String>();
 313  1
         for (String key : row.keySet()) {
 314  2
             String replacedValue = row.get(key);
 315  2
             for (String namedKey : namedParameters.keySet()) {
 316  2
                 String namedValue = namedParameters.get(namedKey);
 317  2
                 replacedValue = replacedValue.replaceAll(namedKey, namedValue);
 318  2
             }
 319  2
             replaced.put(key, replacedValue);
 320  2
         }
 321  1
         return replaced;
 322  
     }
 323  
 
 324  
     public int getRowCount() {
 325  188
         return data.size();
 326  
     }
 327  
 
 328  
     public List<Map<String, String>> getRows() {
 329  48
         List<Map<String, String>> rows = new ArrayList<Map<String, String>>();
 330  137
         for (int row = 0; row < getRowCount(); row++) {
 331  89
             rows.add(getRow(row));
 332  
         }
 333  48
         return rows;
 334  
     }
 335  
 
 336  
     public List<Parameters> getRowsAsParameters() {
 337  2
         return getRowsAsParameters(false);
 338  
     }
 339  
 
 340  
     public List<Parameters> getRowsAsParameters(boolean replaceNamedParameters) {
 341  3
         List<Parameters> rows = new ArrayList<Parameters>();
 342  
 
 343  7
         for (int row = 0; row < getRowCount(); row++) {
 344  4
             rows.add(getRowAsParameters(row, replaceNamedParameters));
 345  
         }
 346  
 
 347  3
         return rows;
 348  
     }
 349  
 
 350  
     private Parameters createParameters(Map<String, String> values) {
 351  12
         return new ConvertedParameters(new ChainedRow(new ConvertedParameters(values, parameterConverters), defaults),
 352  
                 parameterConverters);
 353  
     }
 354  
 
 355  
     public String getHeaderSeparator() {
 356  2
         return headerSeparator;
 357  
     }
 358  
 
 359  
     public String getValueSeparator() {
 360  2
         return valueSeparator;
 361  
     }
 362  
 
 363  
     public String asString() {
 364  55
         if (data.isEmpty()) {
 365  34
             return EMPTY_VALUE;
 366  
         }
 367  21
         return format();
 368  
     }
 369  
 
 370  
     public void outputTo(PrintStream output){
 371  1
         output.print(asString());
 372  1
     }
 373  
     
 374  
     private String format() {
 375  21
         StringBuffer sb = new StringBuffer();
 376  21
         for (String header : headers) {
 377  48
             sb.append(headerSeparator).append(header);
 378  
         }
 379  21
         sb.append(headerSeparator).append(ROW_SEPARATOR);
 380  21
         for (Map<String, String> row : getRows()) {
 381  38
             for (String header : headers) {
 382  88
                 sb.append(valueSeparator);
 383  88
                 sb.append(row.get(header));
 384  
             }
 385  38
             sb.append(valueSeparator).append(ROW_SEPARATOR);
 386  
         }
 387  21
         return sb.toString();
 388  
     }
 389  
 
 390  
     @Override
 391  
     public String toString() {
 392  31
         return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
 393  
     }
 394  
 
 395  
     @SuppressWarnings("serial")
 396  
     public static class RowNotFound extends RuntimeException {
 397  
 
 398  
         public RowNotFound(int row) {
 399  1
             super(Integer.toString(row));
 400  1
         }
 401  
 
 402  
     }
 403  
 }