Capture a selenium screenshot when a test fails and add it to the Cucumber generated report
if the scenario has accessed selenium in its lifetime
@throws InterruptedException
197810
@After
    public void afterScenario(Scenario scenario) throws InterruptedException {
        log.debug("Scenarion finished");
        ScenarioGlobals scenarioGlobals = getCucumberManager().getCurrentScenarioGlobals();
    	TestEnvironment testNev = getSeleniumManager().getAssociatedTestEnvironment();
    	if (testNev != null && scenarioGlobals != null) {
    		boolean scenarioUsedSelenium = testNev.isWebDriverAccessedSince(scenarioGlobals.getScenarioStart());
    		if (scenarioUsedSelenium) {
    			if (scenario.isFailed()) {
    				log.debug("Scenarion failed while using selenium, so capture screenshot");
    				TakesScreenshot seleniumDriver = (TakesScreenshot) SenBotContext.getSeleniumDriver();
					byte[] screenshotAs = seleniumDriver.getScreenshotAs(OutputType.BYTES);
					scenario.embed(screenshotAs, "image/png");
    			}
    		}
    	}
        getCucumberManager().stopNewScenario();
    }
1057196
public static File takeScreenShot(WebElement iframe, WebElement element) {
    return screenshots.takeScreenshot(driver(), iframe, element);
  }
747009
public function takeScreenshotAfterFailedStep(AfterStepScope $event)
    {
        if (!$event->getTestResult()->isPassed()) {
            if ($this->getSession()->getDriver() instanceof Selenium2Driver) {
                $stepLine = $event->getStep()->getLine();
                $time = time();
                $fileName = "./step-{$stepLine}-{$time}.png";
                if (is_writable('.')) {
                    $screenshot = $this->getSession()->getDriver()->getScreenshot();
                    $stepText = $event->getStep()->getText();
                    if (file_put_contents($fileName, $screenshot)) {
                        echo "Screenshot for '{$stepText}' placed in {$fileName}".PHP_EOL;
                    } else {
                        echo "Screenshot failed: {$fileName} is not writable.";
                    }
                }
            }
        }
    }
57182
protected function createScreenshot()
    {
        $image = imagecreatefromstring($this->webDriver->screenshotAsImage());
        if (false === $image) {
            throw new WebDriver_Exception("Invalid screenshot data");
        }
        return $image;
    }
629106
private File captureScreen(TestMethod rootMethod) {
        byte[] screenData = AdapterContainer.globalInstance().captureScreen();
        if (screenData == null) {
            return null;
        }

        // use encoded name to avoid various possible file name encoding problem
        // and to escape invalid file name character (Method name may contain such characters
        // if method is Groovy method, for example).
        File captureFile = new File(String.format("%s/%s/%s/%03d.png", captureRootDir,
                CommonUtils.encodeToSafeAsciiFileNameString(rootMethod.getTestClass().getQualifiedName(), StandardCharsets.UTF_8),
                CommonUtils.encodeToSafeAsciiFileNameString(rootMethod.getSimpleName(), StandardCharsets.UTF_8),
                currentCaptureNo));
        currentCaptureNo++;

        if (captureFile.getParentFile() != null) {
            captureFile.getParentFile().mkdirs();
        }
        FileOutputStream stream = null;
        try {
            stream = new FileOutputStream(captureFile);
            stream.write(screenData);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
        return captureFile;
    }
588074
@Override
	public final Void get() throws InterruptedException, ExecutionException {
		block(0);
		if (!isUnblocked()) throw new InterruptedException();
		if (hasError()) throw new ExecutionException(error);
		if (isCancelled()) throw new ExecutionException(cancelled);
		return null;
	}
340329
function (cb) {
            if (!this._robot) {
                this._robot = Aria.$frameworkWindow.top.SeleniumJavaRobot;
                this._robot.getOffset({
                    fn : this._offsetReceived,
                    scope : this
                });
            }
            if (cb) {
                if (this._robotInitialized) {
                    this.$callback(cb);
                } else {
                    this.$onOnce({
                        "robotInitialized" : cb
                    });
                }
            }
        }
192087
function saveScreenshotIfExists(testResults) {
        var deferred = Q.defer();

        if (testResults.screenshotBuffer) {

            var screenshotFilePath = path.join(resultsDir, testResults.runId, resultScreenshotName);
            fs.writeFile(screenshotFilePath, testResults.screenshotBuffer);

            delete testResults.screenshotBuffer;

        } else {
            deferred.resolve();
        }

        return deferred;
    }
497933
def fail(message = nil)
      if @__assert_pending__ == 0
        if halt_on_fail?
          raise Result::TestFailure, message || ""
        else
          capture_result(Assert::Result::Fail, message || "")
        end
      else
        if halt_on_fail?
          raise Result::TestSkipped, "Pending fail: #{message || ""}"
        else
          capture_result(Assert::Result::Skip, "Pending fail: #{message || ""}")
        end
      end
    end
499331
public void takeScreenshot(String filename) throws IOException {
		File screenshot = ((TakesScreenshot) driver)
				.getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(screenshot, new File(filename));
	}
957194
@Override
    public T get() throws InterruptedException {
        try {
            get(0, null);
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return t;
    }
1266067
def capture_screenshots(cls, name):
        
        screenshot_name = '{}_driver{}' if len(cls.driver_wrappers) > 1 else '{}'
        driver_index = 1
        for driver_wrapper in cls.driver_wrappers:
            if not driver_wrapper.driver:
                continue
            from toolium.jira import add_attachment
            try:
                add_attachment(driver_wrapper.utils.capture_screenshot(screenshot_name.format(name, driver_index)))
            except Exception:
                # Capture exceptions to avoid errors in teardown method due to session timeouts
                pass
            driver_index += 1
628206
@Override
    public T take(final com.oath.cyclops.async.wait.WaitStrategy.Takeable<T> t) throws InterruptedException {
        T result;

        while ((result = t.take()) == null) {

        }

        return result;
    }
172615
def take_screenshot(to_file = nil, opts = {})
        # puts "calling new take screenshot: #{$screenshot_supported}"
        # unless $screenshot_supported
        #   puts " [WARN] Screenhost not supported, check whether win32screenshot gem is installed" 
        #   return
        # end

        if to_file
          screenshot_image_filepath = to_file
        else
          screenshot_image_filename =  "screenshot_" + Time.now.strftime("%m%d%H%M%S") + ".jpg"
          the_dump_dir = opts[:to_dir] || default_dump_dir
          FileUtils.mkdir_p(the_dump_dir) unless File.exists?(the_dump_dir)
          screenshot_image_filepath = File.join(the_dump_dir, screenshot_image_filename)
          screenshot_image_filepath.gsub!("/", "\\") if is_windows?

          FileUtils.rm_f(screenshot_image_filepath) if File.exist?(screenshot_image_filepath)
        end

          # save screenshot with selenium
          @web_browser.driver.save_screenshot(screenshot_image_filepath)
          notify_screenshot_location(screenshot_image_filepath)

      end
1082063
public function screenshot()
    {
        $this->getLogger()->info('Requesting a screenshot from display ID ' . $this->displayId);
        $this->doPut('/display/requestscreenshot/' . $this->displayId);
    }
102134
public static LayoutReport checkPageSpecLayout(WebDriver driver, PageSpec pageSpec, String[]includedTags, String[]excludedTags,
                                           String screenshotFilePath) throws IOException {
        TestSession session = TestSession.current();
        if (session == null) {
            throw new UnregisteredTestSession("Cannot check layout as there was no TestSession created");
        }

        TestReport report = session.getReport();

        File screenshotFile = null;

        if (screenshotFilePath != null) {
            screenshotFile = new File(screenshotFilePath);
            if (!screenshotFile.exists() || !screenshotFile.isFile()) {
                throw new IOException("Couldn't find screenshot in " + screenshotFilePath);
            }
        }

        if (pageSpec == null) {
            throw new IOException("Page spec is not defined");
        }

        List<String> includedTagsList = toList(includedTags);

        LayoutReport layoutReport = Galen.checkLayout(new SeleniumBrowser(driver), pageSpec,
                new SectionFilter(includedTagsList, toList(excludedTags)),
                screenshotFile,
                session.getListener());

        GalenUtils.attachLayoutReport(layoutReport, report, "<unknown>", includedTagsList);
        return layoutReport;
    }
388782
private void captureFailure(AssertionError captured) {
    if (failure != null) {
      // TODO(diamondm) is it worthwhile to add the failures as suppressed exceptions?
      throw new AssertionError(
          lenientFormat(
              "ExpectFailure.whenTesting() caught multiple failures:\n\n%s\n\n%s\n",
              Platform.getStackTraceAsString(failure), Platform.getStackTraceAsString(captured)));
    }
    failure = captured;
  }