1   package com.atlassian.selenium;
2   
3   import org.apache.commons.lang.StringUtils;
4   import org.junit.runner.Description;
5   import org.junit.runner.notification.Failure;
6   import org.junit.runner.notification.RunListener;
7   
8   /**
9    * A listener that captures screenshots if a test fails. Works currently only with FireFox.
10   *
11   * @since 2.0
12   */
13  public class CaptureScreenshotListener extends RunListener
14  {
15      public CaptureScreenshotListener()
16      {
17          super();
18      }
19  
20      @Override
21      public void testFailure(final Failure failure) throws Exception
22      {
23          //This is the output directory configured for the maven surefire plugin.
24          final String reportsDirectory = System.getProperty("reportsDirectory");
25          if (!StringUtils.isEmpty(reportsDirectory))
26          {
27              try
28              {
29                  //Can throw NPE, if selenium client is not initialised yet.
30                  final SeleniumClient seleniumClient = SeleniumStarter.getInstance().getSeleniumClient((SeleniumConfiguration) null);
31                  if (seleniumClient.getBrowser().equals(Browser.FIREFOX))
32                  {
33                      //Default background color is WHITE
34                      seleniumClient.captureEntirePageScreenshot(reportsDirectory + "/" + createSreenshotFileName(failure.getDescription()), "background=#FFFFFF");
35                  }
36              }
37              catch (Exception e)
38              {
39                  //ignored
40              }
41          }
42      }
43  
44      private String createSreenshotFileName(Description description)
45      {
46          final String displayName = description.getDisplayName();
47          int startIndex = displayName.indexOf("(");
48          int endIndex = displayName.lastIndexOf(")");
49          final String filename;
50          if (startIndex != -1 && endIndex != -1)
51          {
52              filename = displayName.substring(startIndex + 1, endIndex);
53          }
54          else
55          {
56              filename = description.getDisplayName();
57          }
58          return filename + ".png";
59      }
60  }