Coverage Report - org.jbehave.core.reporters.FreemarkerViewGenerator
 
Classes in this File Line Coverage Branch Coverage Complexity
FreemarkerViewGenerator
100%
123/123
100%
20/20
1.795
FreemarkerViewGenerator$1
100%
6/6
100%
8/8
1.795
FreemarkerViewGenerator$Report
90%
29/32
83%
5/6
1.795
FreemarkerViewGenerator$ReportCreationFailed
100%
2/2
N/A
1.795
FreemarkerViewGenerator$ReportsTable
90%
30/33
87%
7/8
1.795
FreemarkerViewGenerator$ViewGenerationFailedForTemplate
100%
2/2
N/A
1.795
 
 1  
 package org.jbehave.core.reporters;
 2  
 
 3  
 import static java.util.Arrays.asList;
 4  
 
 5  
 import java.io.File;
 6  
 import java.io.FileInputStream;
 7  
 import java.io.FileReader;
 8  
 import java.io.FileWriter;
 9  
 import java.io.FilenameFilter;
 10  
 import java.io.IOException;
 11  
 import java.io.Writer;
 12  
 import java.util.ArrayList;
 13  
 import java.util.Collection;
 14  
 import java.util.Collections;
 15  
 import java.util.Date;
 16  
 import java.util.Enumeration;
 17  
 import java.util.HashMap;
 18  
 import java.util.List;
 19  
 import java.util.Map;
 20  
 import java.util.Properties;
 21  
 import java.util.SortedMap;
 22  
 import java.util.TreeMap;
 23  
 
 24  
 import org.apache.commons.io.FilenameUtils;
 25  
 import org.apache.commons.io.IOUtils;
 26  
 import org.apache.commons.lang.builder.CompareToBuilder;
 27  
 import org.apache.commons.lang.builder.ToStringBuilder;
 28  
 import org.apache.commons.lang.builder.ToStringStyle;
 29  
 import org.jbehave.core.io.StoryNameResolver;
 30  
 import org.jbehave.core.io.UnderscoredToCapitalized;
 31  
 import org.jbehave.core.model.StoryLanes;
 32  
 import org.jbehave.core.model.StoryMaps;
 33  
 
 34  
 import freemarker.template.Configuration;
 35  
 import freemarker.template.ObjectWrapper;
 36  
 import freemarker.template.Template;
 37  
 import freemarker.template.TemplateException;
 38  
 
 39  
 /**
 40  
  * <p>
 41  
  * Freemarker-based {@link ViewGenerator}, which uses the configured FTL
 42  
  * templates for the views. The default view properties are overridable via the 
 43  
  * method {@link Properties} parameter.  To override, specify the path to the 
 44  
  * new template under the appropriate key:
 45  
  * <p>
 46  
  * The view generator provides the following resources:
 47  
  * 
 48  
  * <pre>
 49  
  * resources.setProperty(&quot;views&quot;, &quot;ftl/jbehave-views.ftl&quot;);
 50  
  * resources.setProperty(&quot;maps&quot;, &quot;ftl/jbehave-maps.ftl&quot;);
 51  
  * resources.setProperty(&quot;navigator&quot;, &quot;ftl/jbehave-navigator.ftl&quot;);
 52  
  * resources.setProperty(&quot;reports&quot;, &quot;ftl/jbehave-reports-with-totals.ftl&quot;);
 53  
  * resources.setProperty(&quot;decorated&quot;, &quot;ftl/jbehave-report-decorated.ftl&quot;);
 54  
  * resources.setProperty(&quot;nonDecorated&quot;, &quot;ftl/jbehave-report-non-decorated.ftl&quot;);
 55  
  * resources.setProperty(&quot;decorateNonHtml&quot;, &quot;true&quot;);
 56  
  * resources.setProperty(&quot;defaultFormats&quot;, &quot;stats&quot;);
 57  
  * resources.setProperty(&quot;viewDirectory&quot;, &quot;view&quot;);
 58  
  * </pre>
 59  
  * </p>
 60  
  * 
 61  
  * @author Mauro Talevi
 62  
  */
 63  
 public class FreemarkerViewGenerator implements ViewGenerator {
 64  
 
 65  
     private final Configuration configuration;
 66  
     private Properties viewProperties;
 67  457
     private List<Report> reports = new ArrayList<Report>();
 68  
     private final StoryNameResolver nameResolver;
 69  
 
 70  
     public FreemarkerViewGenerator() {
 71  457
         this(new UnderscoredToCapitalized());
 72  457
     }
 73  
 
 74  457
     public FreemarkerViewGenerator(StoryNameResolver nameResolver) {
 75  457
         this.nameResolver = nameResolver;
 76  457
         this.configuration = configure();
 77  457
     }
 78  
 
 79  
     public static Properties defaultViewProperties() {
 80  263
         Properties properties = new Properties();
 81  263
         properties.setProperty("views", "ftl/jbehave-views.ftl");
 82  263
         properties.setProperty("maps", "ftl/jbehave-maps.ftl");
 83  263
         properties.setProperty("navigator", "ftl/jbehave-navigator.ftl");
 84  263
         properties.setProperty("reports", "ftl/jbehave-reports-with-totals.ftl");
 85  263
         properties.setProperty("decorated", "ftl/jbehave-report-decorated.ftl");
 86  263
         properties.setProperty("nonDecorated", "ftl/jbehave-report-non-decorated.ftl");
 87  263
         properties.setProperty("decorateNonHtml", "true");
 88  263
         properties.setProperty("defaultFormats", "stats");
 89  263
         properties.setProperty("viewDirectory", "view");
 90  263
         return properties;
 91  
     }
 92  
 
 93  
     private Properties mergeWithDefault(Properties properties) {
 94  17
         Properties merged = defaultViewProperties();
 95  17
         merged.putAll(properties);
 96  17
         return merged;
 97  
     }
 98  
 
 99  
     private void generateViewsIndex(File outputDirectory) {
 100  16
         String outputName = templateResource("viewDirectory") + "/index.html";
 101  16
         String viewsTemplate = templateResource("views");        
 102  16
         Map<String, Object> dataModel = newDataModel();
 103  16
         dataModel.put("date", new Date());
 104  16
         write(outputDirectory, outputName, viewsTemplate, dataModel);        
 105  16
     }
 106  
 
 107  
     public void generateMapsView(File outputDirectory, StoryMaps storyMaps, Properties viewProperties) {
 108  1
         this.viewProperties = mergeWithDefault(viewProperties);
 109  1
         String outputName = templateResource("viewDirectory") + "/maps.html";
 110  1
         String mapsTemplate = templateResource("maps");
 111  1
         Map<String, Object> dataModel = newDataModel();
 112  1
         dataModel.put("storyLanes", new StoryLanes(storyMaps, nameResolver));
 113  1
         dataModel.put("date", new Date());
 114  1
         write(outputDirectory, outputName, mapsTemplate, dataModel);
 115  1
         generateViewsIndex(outputDirectory);
 116  1
     }
 117  
 
 118  
     public void generateReportsView(File outputDirectory, List<String> formats, Properties viewProperties) {
 119  16
         this.viewProperties = mergeWithDefault(viewProperties);
 120  16
         String outputName = templateResource("viewDirectory") + "/reports.html";
 121  16
         String reportsTemplate = templateResource("reports");
 122  16
         List<String> mergedFormats = mergeFormatsWithDefaults(formats);
 123  16
         reports = createReports(readReportFiles(outputDirectory, outputName, mergedFormats));
 124  16
         Map<String, Object> dataModel = newDataModel();
 125  16
         dataModel.put("reportsTable", new ReportsTable(reports, nameResolver));
 126  16
         dataModel.put("date", new Date());
 127  16
         write(outputDirectory, outputName, reportsTemplate, dataModel);
 128  15
         generateViewsIndex(outputDirectory);
 129  15
     }
 130  
 
 131  
     public ReportsCount getReportsCount() {
 132  13
         int stories = reports.size();
 133  13
         int storiesNotAllowed = count("notAllowed", reports);
 134  13
         int storiesPending = count("pending", reports);
 135  13
         int scenarios = count("scenarios", reports);
 136  13
         int scenariosFailed = count("scenariosFailed", reports);
 137  13
         int scenariosNotAllowed = count("scenariosNotAllowed", reports);
 138  13
         int scenariosPending = count("scenariosPending", reports);
 139  13
         return new ReportsCount(stories, storiesNotAllowed, storiesPending, scenarios, scenariosFailed, scenariosNotAllowed, scenariosPending);
 140  
     }
 141  
 
 142  
     int count(String event, Collection<Report> reports) {
 143  80
         int count = 0;
 144  80
         for (Report report : reports) {
 145  80
             Properties stats = report.asProperties("stats");
 146  80
             if (stats.containsKey(event)) {
 147  1
                 count = count + Integer.parseInt((String) stats.get(event));
 148  
             }
 149  80
         }
 150  80
         return count;
 151  
     }
 152  
 
 153  
     private List<String> mergeFormatsWithDefaults(List<String> formats) {
 154  16
         List<String> merged = new ArrayList<String>();
 155  16
         merged.addAll(asList(templateResource("defaultFormats").split(",")));
 156  16
         merged.addAll(formats);
 157  16
         return merged;
 158  
     }
 159  
 
 160  
     List<Report> createReports(Map<String, List<File>> reportFiles) {
 161  
         try {
 162  17
             String decoratedTemplate = templateResource("decorated");
 163  16
             String nonDecoratedTemplate = templateResource("nonDecorated");
 164  16
             String viewDirectory = templateResource("viewDirectory");
 165  16
             boolean decorateNonHtml = Boolean.valueOf(templateResource("decorateNonHtml"));
 166  16
             List<Report> reports = new ArrayList<Report>();
 167  16
             for (String name : reportFiles.keySet()) {
 168  15
                 Map<String, File> filesByFormat = new HashMap<String, File>();
 169  15
                 for (File file : reportFiles.get(name)) {
 170  17
                     String fileName = file.getName();
 171  17
                     String format = FilenameUtils.getExtension(fileName);
 172  17
                     Map<String, Object> dataModel = newDataModel();
 173  17
                     dataModel.put("name", name);
 174  17
                     dataModel.put("body", IOUtils.toString(new FileReader(file)));
 175  17
                     dataModel.put("format", format);
 176  17
                     File outputDirectory = file.getParentFile();
 177  17
                     String outputName = viewDirectory + "/" + fileName;
 178  17
                     String template = decoratedTemplate;
 179  17
                     if (!format.equals("html")) {
 180  15
                         if (decorateNonHtml) {
 181  14
                             outputName = outputName + ".html";
 182  
                         } else {
 183  1
                             template = nonDecoratedTemplate;
 184  
                         }
 185  
                     }
 186  17
                     File written = write(outputDirectory, outputName, template, dataModel);
 187  17
                     filesByFormat.put(format, written);
 188  17
                 }
 189  15
                 reports.add(new Report(name, filesByFormat));
 190  15
             }
 191  16
             return reports;
 192  1
         } catch (Exception e) {
 193  1
             throw new ReportCreationFailed(reportFiles, e);
 194  
         }
 195  
     }
 196  
 
 197  
     SortedMap<String, List<File>> readReportFiles(File outputDirectory, final String outputName,
 198  
             final List<String> formats) {
 199  19
         SortedMap<String, List<File>> reportFiles = new TreeMap<String, List<File>>();
 200  19
         if (outputDirectory == null || !outputDirectory.exists()) {
 201  2
             return reportFiles;
 202  
         }
 203  17
         String[] fileNames = outputDirectory.list(new FilenameFilter() {
 204  
             public boolean accept(File dir, String name) {
 205  126
                 return !name.equals(outputName) && hasFormats(name, formats);
 206  
             }
 207  
 
 208  
             private boolean hasFormats(String name, List<String> formats) {
 209  125
                 for (String format : formats) {
 210  161
                     if (name.endsWith(format)) {
 211  21
                         return true;
 212  
                     }
 213  
                 }
 214  104
                 return false;
 215  
             }
 216  
         });
 217  38
         for (String fileName : fileNames) {
 218  21
             String name = FilenameUtils.getBaseName(fileName);
 219  21
             List<File> filesByName = reportFiles.get(name);
 220  21
             if (filesByName == null) {
 221  17
                 filesByName = new ArrayList<File>();
 222  17
                 reportFiles.put(name, filesByName);
 223  
             }
 224  21
             filesByName.add(new File(outputDirectory, fileName));
 225  
         }
 226  17
         return reportFiles;
 227  
     }
 228  
 
 229  
     private File write(File outputDirectory, String outputName, String resource, Map<String, Object> dataModel) {
 230  
         try {
 231  50
             File file = new File(outputDirectory, outputName);
 232  50
             file.getParentFile().mkdirs();
 233  50
             Writer writer = new FileWriter(file);
 234  50
             process(resource, dataModel, writer);
 235  49
             return file;
 236  1
         } catch (Exception e) {
 237  1
             throw new ViewGenerationFailedForTemplate(resource, e);
 238  
         }
 239  
     }
 240  
 
 241  
     private Configuration configure() {
 242  457
         Configuration configuration = new Configuration();
 243  457
         configuration.setClassForTemplateLoading(FreemarkerViewGenerator.class, "/");
 244  457
         configuration.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
 245  457
         return configuration;
 246  
     }
 247  
 
 248  
     private void process(String resource, Map<String, Object> dataModel, Writer writer) throws TemplateException,
 249  
             IOException {
 250  50
         Template template = configuration.getTemplate(resource);
 251  49
         template.process(dataModel, writer);
 252  49
     }
 253  
 
 254  
     private String templateResource(String format) {
 255  147
         return viewProperties.getProperty(format);
 256  
     }
 257  
 
 258  
     private Map<String, Object> newDataModel() {
 259  50
         return new HashMap<String, Object>();
 260  
     }
 261  
 
 262  
     @SuppressWarnings("serial")
 263  
     public static class ReportCreationFailed extends RuntimeException {
 264  
 
 265  
         public ReportCreationFailed(Map<String, List<File>> reportFiles, Exception cause) {
 266  1
             super("Report creation failed from file " + reportFiles, cause);
 267  1
         }
 268  
     }
 269  
 
 270  
     @SuppressWarnings("serial")
 271  
     public static class ViewGenerationFailedForTemplate extends RuntimeException {
 272  
 
 273  
         public ViewGenerationFailedForTemplate(String resource, Exception cause) {
 274  1
             super(resource, cause);
 275  1
         }
 276  
 
 277  
     }
 278  
 
 279  
     public static class ReportsTable {
 280  
 
 281  16
         private final Map<String, Report> reports = new HashMap<String, Report>();
 282  
         private final StoryNameResolver nameResolver;
 283  
 
 284  16
         public ReportsTable(List<Report> reports, StoryNameResolver nameResolver) {
 285  16
             this.nameResolver = nameResolver;
 286  16
             index(reports);
 287  16
             addTotalsReport();
 288  16
         }
 289  
 
 290  
         private void index(List<Report> reports) {
 291  16
             for (Report report : reports) {
 292  15
                 report.nameAs(nameResolver.resolveName(report.getPath()));
 293  15
                 this.reports.put(report.getName(), report);
 294  
             }
 295  16
         }
 296  
 
 297  
         private void addTotalsReport() {
 298  16
             Report report = totals(reports.values());
 299  16
             report.nameAs(nameResolver.resolveName(report.getPath()));
 300  16
             reports.put(report.getName(), report);
 301  16
         }
 302  
 
 303  
         private Report totals(Collection<Report> values) {
 304  16
             Map<String, Integer> totals = new HashMap<String, Integer>();
 305  16
             for (Report report : values) {
 306  15
                 Map<String, Integer> stats = report.getStats();
 307  15
                 for (String key : stats.keySet()) {
 308  234
                     Integer total = totals.get(key);
 309  234
                     if (total == null) {
 310  234
                         total = 0;
 311  
                     }
 312  234
                     total = total + stats.get(key);
 313  234
                     totals.put(key, total);
 314  234
                 }
 315  15
             }
 316  16
             return new Report("Totals", new HashMap<String, File>(), totals);
 317  
         }
 318  
 
 319  
         public List<Report> getReports() {
 320  0
             List<Report> list = new ArrayList<Report>(reports.values());
 321  0
             Collections.sort(list);
 322  0
             return list;
 323  
         }
 324  
 
 325  
         public List<String> getReportNames() {
 326  15
             List<String> list = new ArrayList<String>(reports.keySet());
 327  15
             Collections.sort(list);
 328  15
             return list;
 329  
         }
 330  
 
 331  
         public Report getReport(String name) {
 332  45
             return reports.get(name);
 333  
         }
 334  
     }
 335  
 
 336  0
     public static class Report implements Comparable<Report> {
 337  
 
 338  
         private final String path;
 339  
         private final Map<String, File> filesByFormat;
 340  
         private Map<String, Integer> stats;
 341  
         private String name;
 342  
 
 343  
         public Report(String path, Map<String, File> filesByFormat) {
 344  16
             this(path, filesByFormat, null);
 345  16
         }
 346  
 
 347  32
         public Report(String path, Map<String, File> filesByFormat, Map<String, Integer> stats) {
 348  32
             this.path = path;
 349  32
             this.filesByFormat = filesByFormat;
 350  32
             this.stats = stats;
 351  32
         }
 352  
 
 353  
         public String getPath() {
 354  31
             return path;
 355  
         }
 356  
 
 357  
         public String getName() {
 358  46
             return name != null ? name : path;
 359  
         }
 360  
 
 361  
         public void nameAs(String name) {
 362  31
             this.name = name;
 363  31
         }
 364  
 
 365  
         public Map<String, File> getFilesByFormat() {
 366  15
             return filesByFormat;
 367  
         }
 368  
 
 369  
         public Properties asProperties(String format) {
 370  94
             Properties p = new Properties();
 371  94
             File stats = filesByFormat.get(format);
 372  
             try {
 373  94
                 p.load(new FileInputStream(stats));
 374  3
             } catch (Exception e) {
 375  
                 // return empty map
 376  91
             }
 377  94
             return p;
 378  
         }
 379  
 
 380  
         public Map<String, Integer> getStats() {
 381  45
             if (stats == null) {
 382  15
                 Properties p = asProperties("stats");
 383  15
                 stats = new HashMap<String, Integer>();
 384  15
                 for (Enumeration<?> e = p.propertyNames(); e.hasMoreElements();) {
 385  234
                     String key = (String) e.nextElement();
 386  234
                     stats.put(key, valueOf(key, p));
 387  234
                 }
 388  
             }
 389  45
             return stats;
 390  
         }
 391  
 
 392  
         private Integer valueOf(String key, Properties p) {
 393  
             try {
 394  234
                 return Integer.valueOf(p.getProperty(key));
 395  234
             } catch (NumberFormatException e) {
 396  234
                 return 0;
 397  
             }
 398  
         }
 399  
 
 400  
         public int compareTo(Report that) {
 401  0
             return CompareToBuilder.reflectionCompare(this.getName(), that.getName());
 402  
         }
 403  
 
 404  
         @Override
 405  
         public String toString() {
 406  0
             return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append(path).toString();
 407  
         }
 408  
     }
 409  
 
 410  
 }