package com.redheap.selenium.junit;

import java.io.File;
import java.io.IOException;

import java.util.logging.Logger;

import org.apache.commons.io.FileUtils;

import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;

public class SavePageSourceOnFailure extends TestWatcher {

    private final File basedir;
    private final WebDriver driver;

    private static final Logger logger = Logger.getLogger(SavePageSourceOnFailure.class.getName());

    public SavePageSourceOnFailure(WebDriver driver) {
        this(driver, new File("."));
    }

    public SavePageSourceOnFailure(WebDriver driver, File basedir) {
        this.driver = driver;
        this.basedir = basedir;
    }

    @Override
    protected void failed(Throwable t, Description description) {
        try {
            File file = new File(basedir, description.getClassName() + "-" + description.getMethodName() + ".txt");
            file.getCanonicalFile().getParentFile().mkdirs();
            logger.finer("dumping page source " + file.getCanonicalPath());
            FileUtils.write(file, driver.getPageSource());
        } catch (IOException e) {
            e.printStackTrace();
            throw new WebDriverException(e);
        }
    }

}

@@ -76,24 +76,46 @@
 Exception;%0A%0A
+import java.util.Set;%0A
 import java.
@@ -135,16 +135,16 @@
 Logger;%0A
-
 %0Aimport 
@@ -898,16 +898,17 @@
   try %7B%0A
+%0A
         
@@ -915,112 +915,527 @@
     
-File file = new File(basedir, description.getClassName() + %22-%22 + description.getMethodName() + %22.txt%22);%0A
+Set%3CString%3E windows = driver.getWindowHandles();%0A            int idx = 0;%0A            String baseFileName = description.getClassName() + %22-%22 + description.getMethodName();%0A            for (String guid : windows) %7B%0A                StringBuilder fileName = new StringBuilder(baseFileName);%0A                if (windows.size() %3E 1) %7B%0A                    fileName.append(%22-%22).append((idx++));%0A                %7D%0A                fileName.append(%22.txt%22);%0A                File file = new File(basedir, fileName.toString());%0A    
     
@@ -1504,16 +1504,20 @@
         
+ 
+   
 logger.f
@@ -1588,54 +1588,316 @@
     
-FileUtils.write(file, driver.getPageSource());
+    try %7B%0A                    driver.switchTo().window(guid);%0A                    FileUtils.write(file, driver.getPageSource());%0A                %7D catch (RuntimeException e) %7B%0A                    // ignore and continue with next window%0A                    e.printStackTrace();%0A                %7D%0A            %7D
 %0A   

save sources of all windows on failure