<commit_before>package nl.hsac.fitnesse.fixture.slim.web;

import nl.hsac.fitnesse.fixture.Environment;
import nl.hsac.fitnesse.fixture.slim.SlimFixture;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.util.SauceLabsHelper;
import nl.hsac.fitnesse.fixture.util.SeleniumHelper;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.*;
import org.openqa.selenium.safari.SafariDriver;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 * Script fixture to set up webdriver to be used by Selenium tests.
 */
public class SeleniumDriverSetup extends SlimFixture {
    public static final String REMOTE_URL_KEY = "SeleniumRemoteUrl";
    private static final String LAST_RUN_SUMMARY = "SeleniumLastRunSummary";
    protected static boolean OVERRIDE_ACTIVE = false;

    /**
     * Sets system property (needed by the WebDriver to be set up).
     * @param propName name of property to set.
     * @param value value to set.
     * @return true.
     */
    public boolean setPropertyValue(String propName, String value) {
        if (OVERRIDE_ACTIVE) {
            return true;
        }

        System.setProperty(propName, value);
        return true;
    }

    /**
     * Creates an instance of the specified class an injects it into SeleniumHelper, so other fixtures can use it.
     * @param driverClassName name of Java class of WebDriver to use.
     * @return true if instance was created and injected into SeleniumHelper.
     * @throws Exception if no instance could be created.
     */
    public boolean startDriver(String driverClassName) throws Exception {
        if (OVERRIDE_ACTIVE) {
            return true;
        }

        final Class<?> driverClass = Class.forName(driverClassName);
        if (!WebDriver.class.isAssignableFrom(driverClass)) {
            throw new SlimFixtureException(false, driverClassName + " does not implement " + WebDriver.class.getName());
        }
        SeleniumHelper.DriverFactory driverFactory = new SeleniumHelper.DriverFactory() {
            @Override
            public void createDriver() {
                try {
                    Object driver = driverClass.newInstance();
                    setDriver((WebDriver) driver);
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };
        WebDriver driver = setAndUseDriverFactory(driverFactory);
        return driver != null;
    }

    /**
     * Starts a local instance of the selenium driver for the specified browser
     * (using defaults to determine the correct class and configuration properties).
     * and injects it into SeleniumHelper, so other fixtures can use it.
     * @param browser name of browser to connect to.
     * @return true if instance was created and injected into SeleniumHelper.
     * @throws Exception if no instance could be created.
     */
    public boolean startDriverFor(String browser) throws Exception {
        if (OVERRIDE_ACTIVE) {
            return true;
        }

        boolean result = false;
        String browserName = browser.toLowerCase();
        if ("firefox".equals(browserName)) {
            result = startDriver(FirefoxDriver.class.getName());
        } else if ("safari".equals(browserName)) {
            result = startDriver(SafariDriver.class.getName());
        } else if ("chrome".equals(browserName)) {
            String driverPath = getExecutable("chromedriver");
            setPropertyValue("webdriver.chrome.driver", driverPath);
            result = startDriver(ChromeDriver.class.getName());
        } else if ("internet explorer".equals(browserName)) {
            String driverPath = getExecutable("IEDriverServer");
            setPropertyValue("webdriver.ie.driver", driverPath);
            result = startDriver(InternetExplorerDriver.class.getName());
        } else if ("phantomjs".equals(browserName)) {
            String driverPath = getExecutable("phantomjs");
            setPropertyValue("phantomjs.binary.path", driverPath);
            result = startDriver(PhantomJSDriver.class.getName());
        } else {
            throw new IllegalArgumentException("No defaults known for: " + browser);
        }
        return result;
    }

    private String getExecutable(String basename) {
        String name = getExecutableForOs(basename);
        return getAbsoluteWebDriverPath(name);
    }

    protected String getAbsoluteWebDriverPath(String executable) {
        String path = executable;
        File f = new File("webdrivers", executable);
        if (f.exists()) {
            path = f.getAbsolutePath();
        } else {
            f = new File("wiki/webdrivers", executable);
            if (f.exists()) {
                path = f.getAbsolutePath();
            }
        }
        return path;
    }

    protected String getExecutableForOs(String basename) {
        String name = basename;
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            name += ".exe";
        } else if (os.contains("mac")) {
            name = "osx" + File.separator + basename;
        } else if (os.contains("linux")) {
            name = "linux" + File.separator + basename;
        }
        return name;
    }

    /**
     * Connects SeleniumHelper to a remote web driver, without specifying browser version.
     * @param browser name of browser to connect to.
     * @param url url to connect to browser.
     * @return true.
     * @throws MalformedURLException if supplied url can not be transformed to URL.
     */
    public boolean connectToDriverForAt(String browser, String url)
            throws MalformedURLException {
        return connectToDriverForVersionOnAt(browser, "", Platform.ANY.name(), url);
    }

    /**
     * Connects SeleniumHelper to a remote web driver, without specifying browser version.
     * @param browser name of browser to connect to.
     * @param platformName platform browser must run on.
     * @param url url to connect to browser.
     * @return true.
     * @throws MalformedURLException if supplied url can not be transformed to URL.
     */
    public boolean connectToDriverForOnAt(String browser, String platformName, String url)
            throws MalformedURLException {
        return connectToDriverForVersionOnAt(browser, "", platformName, url);
    }

    /**
     * Connects SeleniumHelper to a remote web driver.
     * @param browser name of browser to connect to.
     * @param version version of browser.
     * @param platformName platform browser must run on.
     * @param url url to connect to browser.
     * @return true.
     * @throws MalformedURLException if supplied url can not be transformed to URL.
     */
    public boolean connectToDriverForVersionOnAt(String browser, String version, String platformName, String url)
            throws MalformedURLException {
        Platform platform = Platform.valueOf(platformName);
        DesiredCapabilities desiredCapabilities = new DesiredCapabilities(browser, version, platform);
        desiredCapabilities.setVersion(version);
        return createAndSetRemoteDriver(url, desiredCapabilities);
    }

    public boolean connectToDriverAtWithCapabilities(String url, Map<String, Object> capabilities)
            throws MalformedURLException {
        DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
        for (Map.Entry<String, Object> capability : capabilities.entrySet()) {
            desiredCapabilities.setCapability(capability.getKey(), capability.getValue());
        }
        return createAndSetRemoteDriver(url, desiredCapabilities);
    }

    public String driverDescription() {
        String result = null;
        WebDriver driver = getHelper().driver();
        if (driver != null) {
            StringBuilder builder = new StringBuilder("<div>");
            builder.append("<pre>");
            builder.append(driver.getClass().getName());
            builder.append("</pre>");

            if (driver instanceof RemoteWebDriver) {
                RemoteWebDriver remoteDriver = (RemoteWebDriver) driver;

                URL lastRemoteUrl = getLastRemoteUrl();
                if (lastRemoteUrl != null) {
                    builder.append(" at <strong>");
                    builder.append(lastRemoteUrl.getHost());
                    builder.append("</strong>");
                }<commit_msg>public boolean connectToDriverAtWithCapabilities(String url, String capabilitiesInJson)<commit_after>package nl.hsac.fitnesse.fixture.slim.web;

import nl.hsac.fitnesse.fixture.Environment;
import nl.hsac.fitnesse.fixture.slim.SlimFixture;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.util.SauceLabsHelper;
import nl.hsac.fitnesse.fixture.util.SeleniumHelper;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.*;
import org.openqa.selenium.safari.SafariDriver;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
/**
 * Script fixture to set up webdriver to be used by Selenium tests.
 */
public class SeleniumDriverSetup extends SlimFixture {
    public static final String REMOTE_URL_KEY = "SeleniumRemoteUrl";
    private static final String LAST_RUN_SUMMARY = "SeleniumLastRunSummary";
    protected static boolean OVERRIDE_ACTIVE = false;

    /**
     * Sets system property (needed by the WebDriver to be set up).
     * @param propName name of property to set.
     * @param value value to set.
     * @return true.
     */
    public boolean setPropertyValue(String propName, String value) {
        if (OVERRIDE_ACTIVE) {
            return true;
        }

        System.setProperty(propName, value);
        return true;
    }

    /**
     * Creates an instance of the specified class an injects it into SeleniumHelper, so other fixtures can use it.
     * @param driverClassName name of Java class of WebDriver to use.
     * @return true if instance was created and injected into SeleniumHelper.
     * @throws Exception if no instance could be created.
     */
    public boolean startDriver(String driverClassName) throws Exception {
        if (OVERRIDE_ACTIVE) {
            return true;
        }

        final Class<?> driverClass = Class.forName(driverClassName);
        if (!WebDriver.class.isAssignableFrom(driverClass)) {
            throw new SlimFixtureException(false, driverClassName + " does not implement " + WebDriver.class.getName());
        }
        SeleniumHelper.DriverFactory driverFactory = new SeleniumHelper.DriverFactory() {
            @Override
            public void createDriver() {
                try {
                    Object driver = driverClass.newInstance();
                    setDriver((WebDriver) driver);
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };
        WebDriver driver = setAndUseDriverFactory(driverFactory);
        return driver != null;
    }

    /**
     * Starts a local instance of the selenium driver for the specified browser
     * (using defaults to determine the correct class and configuration properties).
     * and injects it into SeleniumHelper, so other fixtures can use it.
     * @param browser name of browser to connect to.
     * @return true if instance was created and injected into SeleniumHelper.
     * @throws Exception if no instance could be created.
     */
    public boolean startDriverFor(String browser) throws Exception {
        if (OVERRIDE_ACTIVE) {
            return true;
        }

        boolean result = false;
        String browserName = browser.toLowerCase();
        if ("firefox".equals(browserName)) {
            result = startDriver(FirefoxDriver.class.getName());
        } else if ("safari".equals(browserName)) {
            result = startDriver(SafariDriver.class.getName());
        } else if ("chrome".equals(browserName)) {
            String driverPath = getExecutable("chromedriver");
            setPropertyValue("webdriver.chrome.driver", driverPath);
            result = startDriver(ChromeDriver.class.getName());
        } else if ("internet explorer".equals(browserName)) {
            String driverPath = getExecutable("IEDriverServer");
            setPropertyValue("webdriver.ie.driver", driverPath);
            result = startDriver(InternetExplorerDriver.class.getName());
        } else if ("phantomjs".equals(browserName)) {
            String driverPath = getExecutable("phantomjs");
            setPropertyValue("phantomjs.binary.path", driverPath);
            result = startDriver(PhantomJSDriver.class.getName());
        } else {
            throw new IllegalArgumentException("No defaults known for: " + browser);
        }
        return result;
    }

    private String getExecutable(String basename) {
        String name = getExecutableForOs(basename);
        return getAbsoluteWebDriverPath(name);
    }

    protected String getAbsoluteWebDriverPath(String executable) {
        String path = executable;
        File f = new File("webdrivers", executable);
        if (f.exists()) {
            path = f.getAbsolutePath();
        } else {
            f = new File("wiki/webdrivers", executable);
            if (f.exists()) {
                path = f.getAbsolutePath();
            }
        }
        return path;
    }

    protected String getExecutableForOs(String basename) {
        String name = basename;
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            name += ".exe";
        } else if (os.contains("mac")) {
            name = "osx" + File.separator + basename;
        } else if (os.contains("linux")) {
            name = "linux" + File.separator + basename;
        }
        return name;
    }

    /**
     * Connects SeleniumHelper to a remote web driver, without specifying browser version.
     * @param browser name of browser to connect to.
     * @param url url to connect to browser.
     * @return true.
     * @throws MalformedURLException if supplied url can not be transformed to URL.
     */
    public boolean connectToDriverForAt(String browser, String url)
            throws MalformedURLException {
        return connectToDriverForVersionOnAt(browser, "", Platform.ANY.name(), url);
    }

    /**
     * Connects SeleniumHelper to a remote web driver, without specifying browser version.
     * @param browser name of browser to connect to.
     * @param platformName platform browser must run on.
     * @param url url to connect to browser.
     * @return true.
     * @throws MalformedURLException if supplied url can not be transformed to URL.
     */
    public boolean connectToDriverForOnAt(String browser, String platformName, String url)
            throws MalformedURLException {
        return connectToDriverForVersionOnAt(browser, "", platformName, url);
    }

    /**
     * Connects SeleniumHelper to a remote web driver.
     * @param browser name of browser to connect to.
     * @param version version of browser.
     * @param platformName platform browser must run on.
     * @param url url to connect to browser.
     * @return true.
     * @throws MalformedURLException if supplied url can not be transformed to URL.
     */
    public boolean connectToDriverForVersionOnAt(String browser, String version, String platformName, String url)
            throws MalformedURLException {
        Platform platform = Platform.valueOf(platformName);
        DesiredCapabilities desiredCapabilities = new DesiredCapabilities(browser, version, platform);
        desiredCapabilities.setVersion(version);
        return createAndSetRemoteDriver(url, desiredCapabilities);
    }

    public boolean connectToDriverAtWithCapabilities(String url, Map<String, Object> capabilities)
            throws MalformedURLException {
        DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
        for (Map.Entry<String, Object> capability : capabilities.entrySet()) {
            desiredCapabilities.setCapability(capability.getKey(), capability.getValue());
        }
        return createAndSetRemoteDriver(url, desiredCapabilities);
    }

    private Map<String, Object> jsonObjectToMap(JSONObject jsonObject) throws JSONException {
        // Assume you have a Map<String, String> in JSONObject
        @SuppressWarnings("unchecked")
        Iterator<String> nameItr = jsonObject.keys();
        Map<String, Object> outMap = new HashMap<String, Object>();
        while(nameItr.hasNext()) {
            String name = nameItr.next();
            outMap.put(name, jsonObject.get(name));
        }
        return  outMap;
    }

    public boolean connectToDriverAtWithCapabilities(String url, String capabilitiesInJson)
            throws MalformedURLException {
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(capabilitiesInJson);
        } catch (JSONException e) {
            throw new RuntimeException("Unable to interpret capabilities", e);
        }

        Map<String, Object> desiredCapabilities;
        try {
            desiredCapabilities = jsonObjectToMap(jsonObject);
        } catch (JSONException e) {
            throw new RuntimeException("Unable to fetch required fields from json string", e);
        }

        return connectToDriverAtWithCapabilities (url, desiredCapabilities);
    }

    public String driverDescription() {
        String result = null;
        WebDriver driver = getHelper().driver();
        if (driver != null) {
            StringBuilder builder = new StringBuilder("<div>");
            builder.append("<pre>");
            builder.append(driver.getClass().getName());
            builder.append("</pre>");

            if (driver instanceof RemoteWebDriver) {
                RemoteWebDriver remoteDriver = (RemoteWebDriver) driver;

                URL lastRemoteUrl = getLastRemoteUrl();
                if (lastRemoteUrl != null) {
                    builder.append(" at <strong>");
                    builder.append(lastRemoteUrl.getHost());
                    builder.append("</strong>");
                }
{'fraction_non_alphanumeric': 0.0896458050360464, 'fraction_numerical': 0.0, 'mean_word_length': 2.6132502831257076, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5630517', 'n_tokens_mistral': 4982, 'n_tokens_neox': 4840, 'n_words': 1388}