Example usage for org.openqa.selenium.safari SafariDriver SafariDriver

List of usage examples for org.openqa.selenium.safari SafariDriver SafariDriver

Introduction

In this page you can find the example usage for org.openqa.selenium.safari SafariDriver SafariDriver.

Prototype

public SafariDriver() 

Source Link

Document

Initializes a new SafariDriver} class with default SafariOptions .

Usage

From source file:org.bigtester.ate.model.page.atewebdriver.MySafariDriver.java

License:Apache License

/**
 * {@inheritDoc}//from   w  w  w.  ja v  a 2s.  c  o m
 */
@Override
public WebDriver getWebDriverInstance() {
    WebDriver retVal = getWebDriver();

    if (null == retVal) {
        retVal = new SafariDriver();
    }
    setWebDriver(retVal);
    return retVal;
    /*
     * if ( null == retVal) { if (null == getBrowserProfile().getProfile())
     * { retVal = new SafariDriver(); } else { retVal = new
     * SafariDriver(getBrowserProfile().getProfile()); }
     * setWebDriver(retVal);
     * 
     * } return retVal;
     */
}

From source file:org.emonocot.portal.driver.WebDriverFacade.java

License:Open Source License

/**
 *
 * @return the webdriver//  w w  w  .j  av a 2  s  .  c o m
 * @throws IOException if there is a problem loading the
 *                     properties file
 */
private WebDriver createWebDriver() throws IOException {
    Resource propertiesFile = new ClassPathResource("META-INF/spring/application.properties");
    Properties properties = new Properties();
    properties.load(propertiesFile.getInputStream());
    String webdriverMode = properties.getProperty("selenium.webdriver.mode", "local");
    String driverName = properties.getProperty("selenium.webdriver.impl",
            "org.openqa.selenium.firefox.FirefoxDriver");
    WebDriverBrowserType browser = WebDriverBrowserType.fromString(driverName);
    String display = properties.getProperty("selenium.display.port", ":0");
    if (webdriverMode.equals("local")) {
        switch (browser) {
        case CHROME:
            String chromeLocation = properties.getProperty("selenium.webdriver.chromedriver.location");
            Map<String, String> environment = new HashMap<String, String>();
            environment.put("DISPLAY", display);
            ChromeDriverService chromeService = new ChromeDriverService.Builder()
                    .usingDriverExecutable(new File(chromeLocation)).usingAnyFreePort()
                    .withEnvironment(environment).build();
            chromeService.start();
            return new RemoteWebDriver(chromeService.getUrl(), DesiredCapabilities.chrome());
        case SAFARI:
            return new SafariDriver();
        case INTERNET_EXPLORER:
            String internetExplorerLocation = properties.getProperty("selenium.webdriver.ie.location");
            InternetExplorerDriverService ieService = InternetExplorerDriverService.createDefaultService();
            ieService.start();
            return new RemoteWebDriver(ieService.getUrl(), DesiredCapabilities.internetExplorer());
        case FIREFOX:
        default:
            FirefoxBinary firefoxBinary = new FirefoxBinary();
            firefoxBinary.setEnvironmentProperty("DISPLAY", display);
            ProfilesIni allProfiles = new ProfilesIni();
            FirefoxProfile profile = allProfiles.getProfile("default");
            return new FirefoxDriver(firefoxBinary, profile);
        }
    } else {

        DesiredCapabilities capabilities = new DesiredCapabilities();
        switch (browser) {
        case CHROME:
            capabilities = DesiredCapabilities.chrome();
            break;
        case INTERNET_EXPLORER:
            capabilities = DesiredCapabilities.internetExplorer();
            break;
        case SAFARI:
            capabilities = DesiredCapabilities.safari();
            break;
        case FIREFOX:
        default:
            capabilities = DesiredCapabilities.firefox();
        }
        String platformName = properties.getProperty("selenium.webdriver.platformName", "LINUX");
        WebDriverPlatformType platform = WebDriverPlatformType.valueOf(platformName);
        switch (platform) {
        case MAC:
            capabilities.setPlatform(Platform.MAC);
            break;
        case WINDOWS:
            capabilities.setPlatform(Platform.WINDOWS);
            break;
        case LINUX:
        default:
            capabilities.setPlatform(Platform.LINUX);
        }
        return new RemoteWebDriver(new URL("http://build.e-monocot.org:4444/wd/hub"), capabilities);
    }
}

From source file:org.glassfish.tyrus.tests.qa.SeleniumToolkit.java

License:Open Source License

public void setUpSafari() {
    try {//from   w  w  w .j  a  v a 2  s. c  o m
        //System.setProperty("webdriver.safari.driver", getEnv("SAFARI_EXTENSION"));
        driver = new SafariDriver();
        commonBrowserSetup();
        logger.log(Level.INFO, "Safari Setup PASSED");
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Safari Setup FAILED: {0}", ex.getLocalizedMessage());
        ex.printStackTrace();
    } finally {
        assert driver != null : "Driver is null";
    }
}

From source file:org.gradle.needle.selenium.BrowserFactory.java

License:Apache License

private void setupBrowserCoreType(int type) {
    if (type == 1) {
        browserCore = new FirefoxDriver();
        logger.info(" Firefox");
        return;//from  w w  w. j  ava2s  .  co  m
    }
    if (type == 2) {
        chromeServer = new ChromeDriverService.Builder()
                .usingDriverExecutable(new File(GlobalSettings.chromeDriverPath)).usingAnyFreePort().build();
        try {
            chromeServer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));
        browserCore = new RemoteWebDriver(chromeServer.getUrl(), capabilities);
        logger.info("Chrome");
        return;
    }
    if (type == 3) {
        System.setProperty("webdriver.ie.driver", GlobalSettings.ieDriverPath);
        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
                true);
        browserCore = new InternetExplorerDriver(capabilities);
        logger.info(" IE ");
        return;
    }
    if (type == 4) {
        browserCore = new SafariDriver();
        logger.info(" Safari ");
        return;
    }

    Assert.fail("Incorrect browser type");
}

From source file:org.jitsi.meet.test.ConferenceFixture.java

License:Apache License

/**
 * Starts a <tt>WebDriver</tt> instance using default settings.
 * @param browser the browser type./*from   w ww .  j  a  v  a  2  s .c  o m*/
 * @param participant the participant we are creating a driver for.
 * @return the <tt>WebDriver</tt> instance.
 */
private static WebDriver startDriverInstance(BrowserType browser, Participant participant) {
    // by default we load chrome, but we can load safari or firefox
    if (browser == BrowserType.firefox) {
        String browserBinary = System.getProperty(BROWSER_FF_BINARY_NAME_PROP);
        if (browserBinary != null && browserBinary.trim().length() > 0) {
            File binaryFile = new File(browserBinary);
            if (binaryFile.exists())
                System.setProperty("webdriver.firefox.bin", browserBinary);
        }

        FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference("media.navigator.permission.disabled", true);
        // Enables tcp in firefox, disabled by default in 44
        profile.setPreference("media.peerconnection.ice.tcp", true);
        profile.setAcceptUntrustedCertificates(true);

        profile.setPreference("webdriver.log.file", FailureListener.createLogsFolder() + "/firefox-js-console-"
                + getParticipantName(participant) + ".log");

        System.setProperty("webdriver.firefox.logfile", FailureListener.createLogsFolder() + "/firefox-console-"
                + getParticipantName(participant) + ".log");

        return new FirefoxDriver(profile);
    } else if (browser == BrowserType.safari) {
        return new SafariDriver();
    } else if (browser == BrowserType.ie) {
        DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
        caps.setCapability("ignoreZoomSetting", true);
        System.setProperty("webdriver.ie.driver.silent", "true");

        return new InternetExplorerDriver(caps);
    } else {
        System.setProperty("webdriver.chrome.verboseLogging", "true");
        System.setProperty("webdriver.chrome.logfile", FailureListener.createLogsFolder() + "/chrome-console-"
                + getParticipantName(participant) + ".log");

        DesiredCapabilities caps = DesiredCapabilities.chrome();
        LoggingPreferences logPrefs = new LoggingPreferences();
        logPrefs.enable(LogType.BROWSER, Level.ALL);
        caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

        final ChromeOptions ops = new ChromeOptions();
        ops.addArguments("use-fake-ui-for-media-stream");
        ops.addArguments("use-fake-device-for-media-stream");
        ops.addArguments("disable-extensions");
        ops.addArguments("disable-plugins");
        ops.addArguments("mute-audio");

        String disProp = System.getProperty(DISABLE_NOSANBOX_PARAM);
        if (disProp == null && !Boolean.parseBoolean(disProp)) {
            ops.addArguments("no-sandbox");
            ops.addArguments("disable-setuid-sandbox");
        }

        // starting version 46 we see crashes of chrome GPU process when
        // running in headless mode
        // which leaves the browser opened and selenium hang forever.
        // There are reports that in older version crashes like that will
        // fallback to software graphics, we try to disable gpu for now
        ops.addArguments("disable-gpu");

        String browserProp;
        if (participant == Participant.secondParticipantDriver)
            browserProp = BROWSER_CHROME_BINARY_SECOND_NAME_PROP;
        else
            browserProp = BROWSER_CHROME_BINARY_OWNER_NAME_PROP;

        String browserBinary = System.getProperty(browserProp);
        if (browserBinary != null && browserBinary.trim().length() > 0) {
            File binaryFile = new File(browserBinary);
            if (binaryFile.exists())
                ops.setBinary(binaryFile);
        }

        if (fakeStreamAudioFName != null) {
            ops.addArguments("use-file-for-fake-audio-capture=" + fakeStreamAudioFName);
        }

        if (fakeStreamVideoFName != null) {
            ops.addArguments("use-file-for-fake-video-capture=" + fakeStreamVideoFName);
        }

        //ops.addArguments("vmodule=\"*media/*=3,*turn*=3\"");
        ops.addArguments("enable-logging");
        ops.addArguments("vmodule=*=3");

        caps.setCapability(ChromeOptions.CAPABILITY, ops);

        try {
            final ExecutorService pool = Executors.newFixedThreadPool(1);
            // we will retry four times for 1 minute to obtain
            // the chrome driver, on headless environments chrome hangs
            // and we wait forever
            for (int i = 0; i < 2; i++) {
                Future<ChromeDriver> future = null;
                try {
                    future = pool.submit(new Callable<ChromeDriver>() {
                        @Override
                        public ChromeDriver call() throws Exception {
                            long start = System.currentTimeMillis();
                            ChromeDriver resDr = new ChromeDriver(ops);
                            System.err.println("ChromeDriver created for:"
                                    + (System.currentTimeMillis() - start) + " ms.");
                            return resDr;
                        }
                    });

                    ChromeDriver res = future.get(2, TimeUnit.MINUTES);
                    if (res != null)
                        return res;
                } catch (TimeoutException te) {
                    // cancel current task
                    if (future != null)
                        future.cancel(true);

                    System.err.println("Timeout waiting for "
                            + "chrome instance! We will retry now, this was our" + "attempt " + i);
                }

            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        // keep the old code
        System.err.println("Just create ChromeDriver, may hang!");
        return new ChromeDriver(ops);
    }
}

From source file:org.jitsi.meet.test.web.WebParticipantFactory.java

License:Apache License

/**
 * Starts a <tt>WebDriver</tt> instance using default settings.
 * @param options the options to use when creating the driver.
 * @return the <tt>WebDriver</tt> instance.
 *///  www  . j  a v a 2s. c o  m
private WebDriver startWebDriver(WebParticipantOptions options) {
    ParticipantType participantType = options.getParticipantType();
    String version = options.getVersion();
    File browserBinaryAPath = getFile(options, options.getBinary());

    boolean isRemote = options.isRemote();

    // by default we load chrome, but we can load safari or firefox
    if (participantType.isFirefox()) {
        FirefoxDriverManager.getInstance().setup();

        if (browserBinaryAPath != null && (browserBinaryAPath.exists() || isRemote)) {
            System.setProperty("webdriver.firefox.bin", browserBinaryAPath.getAbsolutePath());
        }

        FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference("media.navigator.permission.disabled", true);
        // Enables tcp in firefox, disabled by default in 44
        profile.setPreference("media.peerconnection.ice.tcp", true);
        profile.setPreference("media.navigator.streams.fake", true);
        profile.setAcceptUntrustedCertificates(true);

        profile.setPreference("webdriver.log.file",
                FailureListener.createLogsFolder() + "/firefox-js-console-" + options.getName() + ".log");

        System.setProperty("webdriver.firefox.logfile",
                FailureListener.createLogsFolder() + "/firefox-console-" + options.getName() + ".log");

        if (isRemote) {
            FirefoxOptions ffOptions = new FirefoxOptions();
            ffOptions.setProfile(profile);

            if (version != null && version.length() > 0) {
                ffOptions.setCapability(CapabilityType.VERSION, version);
            }

            return new RemoteWebDriver(options.getRemoteDriverAddress(), ffOptions);
        }

        return new FirefoxDriver(new FirefoxOptions().setProfile(profile));
    } else if (participantType == ParticipantType.safari) {
        // You must enable the 'Allow Remote Automation' option in
        // Safari's Develop menu to control Safari via WebDriver.
        // In Safari->Preferences->Websites, select Camera,
        // and select Allow for "When visiting other websites"
        if (isRemote) {
            return new RemoteWebDriver(options.getRemoteDriverAddress(), new SafariOptions());
        }
        return new SafariDriver();
    } else if (participantType == ParticipantType.edge) {
        InternetExplorerDriverManager.getInstance().setup();

        InternetExplorerOptions ieOptions = new InternetExplorerOptions();
        ieOptions.ignoreZoomSettings();

        System.setProperty("webdriver.ie.driver.silent", "true");

        return new InternetExplorerDriver(ieOptions);
    } else {
        ChromeDriverManager.getInstance().setup();

        System.setProperty("webdriver.chrome.verboseLogging", "true");
        System.setProperty("webdriver.chrome.logfile",
                FailureListener.createLogsFolder() + "/chrome-console-" + options.getName() + ".log");

        LoggingPreferences logPrefs = new LoggingPreferences();
        logPrefs.enable(LogType.BROWSER, Level.ALL);

        final ChromeOptions ops = new ChromeOptions();
        ops.addArguments("use-fake-ui-for-media-stream");
        ops.addArguments("use-fake-device-for-media-stream");
        ops.addArguments("disable-plugins");
        ops.addArguments("mute-audio");
        ops.addArguments("disable-infobars");
        // Since chrome v66 there are new autoplay policies, which broke
        // shared video tests, disable no-user-gesture to make it work
        ops.addArguments("autoplay-policy=no-user-gesture-required");

        if (options.getChromeExtensionId() != null) {
            try {
                ops.addExtensions(downloadExtension(options.getChromeExtensionId()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        ops.addArguments("auto-select-desktop-capture-source=Entire screen");

        ops.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

        if (options.isChromeSandboxDisabled()) {
            ops.addArguments("no-sandbox");
            ops.addArguments("disable-setuid-sandbox");
        }

        if (options.isHeadless()) {
            ops.addArguments("headless");
            ops.addArguments("window-size=1200x600");
        }

        // starting version 46 we see crashes of chrome GPU process when
        // running in headless mode
        // which leaves the browser opened and selenium hang forever.
        // There are reports that in older version crashes like that will
        // fallback to software graphics, we try to disable gpu for now
        ops.addArguments("disable-gpu");

        if (browserBinaryAPath != null && (browserBinaryAPath.exists() || isRemote)) {
            ops.setBinary(browserBinaryAPath.getAbsolutePath());
        }

        File uplinkFile = getFile(options, options.getUplink());
        if (uplinkFile != null) {
            ops.addArguments("uplink=" + uplinkFile.getAbsolutePath());
        }

        File downlinkFile = getFile(options, options.getDownlink());
        if (downlinkFile != null) {
            ops.addArguments("downlink=" + downlinkFile.getAbsolutePath());
        }

        String profileDirectory = options.getProfileDirectory();
        if (profileDirectory != null && profileDirectory != "") {
            ops.addArguments("user-data-dir=" + profileDirectory);
        }

        File fakeStreamAudioFile = getFile(options, options.getFakeStreamAudioFile());
        if (fakeStreamAudioFile != null) {
            ops.addArguments("use-file-for-fake-audio-capture=" + fakeStreamAudioFile.getAbsolutePath());
        }

        File fakeStreamVideoFile = getFile(options, options.getFakeStreamVideoFile());
        if (fakeStreamVideoFile != null) {
            ops.addArguments("use-file-for-fake-video-capture=" + fakeStreamVideoFile.getAbsolutePath());
        }

        //ops.addArguments("vmodule=\"*media/*=3,*turn*=3\"");
        ops.addArguments("enable-logging");
        ops.addArguments("vmodule=*=3");

        if (isRemote) {
            if (version != null && version.length() > 0) {
                ops.setCapability(CapabilityType.VERSION, version);
            }

            return new RemoteWebDriver(options.getRemoteDriverAddress(), ops);
        }

        try {
            final ExecutorService pool = Executors.newFixedThreadPool(1);
            // we will retry four times for 1 minute to obtain
            // the chrome driver, on headless environments chrome hangs
            // and we wait forever
            for (int i = 0; i < 2; i++) {
                Future<ChromeDriver> future = null;
                try {
                    future = pool.submit(() -> {
                        long start = System.currentTimeMillis();
                        ChromeDriver resDr = new ChromeDriver(ops);
                        TestUtils.print(
                                "ChromeDriver created for:" + (System.currentTimeMillis() - start) + " ms.");
                        return resDr;
                    });

                    ChromeDriver res = future.get(2, TimeUnit.MINUTES);
                    if (res != null)
                        return res;
                } catch (TimeoutException te) {
                    // cancel current task
                    future.cancel(true);

                    TestUtils.print("Timeout waiting for " + "chrome instance! We will retry now, this was our"
                            + "attempt " + i);
                }

            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        // keep the old code
        TestUtils.print("Just create ChromeDriver, may hang!");
        return new ChromeDriver(ops);
    }
}

From source file:org.opencastproject.loadtest.engage.LoadTestEngage.java

License:Educational Community License

/**
 * Create a new load test for an engage server.
 * //  w w w.  j  a  v a 2s  .c o m
 * @param name
 *          The name of this instance for logging purposes.
 * @param engageServerUrl
 *          The location of the engage server to test.
 * @param episodeList
 *          The list of ids of episodes that we can play in the engage server.
 * @param watchTime
 *          The amount of time to watch a video before moving onto the next one.
 * @param guiSettings
 *          The settings to interact with the gui in the browser such as user/pass and the ids of those fields.
 * @param browserToUse
 *          The browser to use in this test.
 */
public LoadTestEngage(String name, String engageServerUrl, LinkedList<String> episodeList, int watchTime,
        GuiSettings guiSettings, Main.BrowserToUse browserToUse) {
    this.name = name;
    this.engageServerUrl = engageServerUrl;
    this.episodeList = episodeList;
    this.watchTime = watchTime;
    this.guiSettings = guiSettings;

    if (browserToUse == Main.BrowserToUse.Chrome) {
        driver = new ChromeDriver();
    } else if (browserToUse == Main.BrowserToUse.Safari) {
        driver = new SafariDriver();
    } else if (browserToUse == Main.BrowserToUse.IE) {
        driver = new InternetExplorerDriver();
    } else {
        driver = new FirefoxDriver();
    }
}

From source file:org.usapi.SeleniumFactory.java

License:Apache License

/**
 * Returns an instance of WebDriver./* w w w  .ja  v a2s . co m*/
 *
 * This is a singleton that is instantiated with parameters 
 * from system properties with overrides
 */
public static WebDriver getWebDriverInstance() {
    if (webDriver == null) {
        String browser = PropertyHelper.getSeleniumBrowserCommand();

        String seleniumServerHost = PropertyHelper.getSeleniumServerHost();
        String seleniumServerPort = PropertyHelper.getSeleniumServerPort();
        // if selenium server host/port properties are set, they were passed in via 
        // .properties or -D.  Either way, this tells us that we are running on the
        // grid and need to instantiate our web driver such that it knows to use
        // selenium server
        if (seleniumServerHost.length() > 0 && seleniumServerPort.length() > 0) {
            URL seleniumServerUrl = null;
            try {
                seleniumServerUrl = new URL(
                        "http://" + seleniumServerHost + ":" + seleniumServerPort + "/wd/hub");
            } catch (MalformedURLException e) {
                // this should never happen, as the default values for serverHost and port are localhost and 4444.  Only if
                // overrides (from .properties or cmd line) result in an invalid URL this exception handler would get invoked.
                log.error("Invalid value for Selenium Server Host or Selenium Server Port.  Provided values: <"
                        + seleniumServerHost + "> <" + seleniumServerPort + ">");

            }
            DesiredCapabilities capability = getDesiredCapabilities(browser);
            if (browser.toLowerCase().contains(BROWSER_TYPE_FIREFOX)) {
                capability.setCapability("nativeEvents", PropertyHelper.getEnableNativeEvents());
                capability.setCapability("name", "Remote File Upload using Selenium 2's FileDetectors");
            }
            RemoteWebDriver rwd = new RemoteWebDriver(seleniumServerUrl, capability);
            rwd.setFileDetector(new LocalFileDetector());
            webDriver = new Augmenter().augment((WebDriver) rwd);
        }
        // no, we are not running on the grid.  Just instantiate the driver for the desired
        // browser directly.
        else {
            if (browser.toLowerCase().contains(BROWSER_TYPE_FIREFOX)) {
                FirefoxProfile p = new FirefoxProfile();
                p.setEnableNativeEvents(PropertyHelper.getEnableNativeEvents());
                webDriver = new FirefoxDriver(p);
            } else if (browser.toLowerCase().contains(BROWSER_TYPE_IEXPLORE)) {
                webDriver = new InternetExplorerDriver();
            } else if (browser.toLowerCase().contains(BROWSER_TYPE_CHROME)) {
                webDriver = new RemoteWebDriver(getChromeDriverURL(), DesiredCapabilities.chrome());
                webDriver = new Augmenter().augment((WebDriver) webDriver);
            } else if (browser.toLowerCase().contains(BROWSER_TYPE_SAFARI)) {
                webDriver = new SafariDriver();
            } else if (browser.toLowerCase().contains(BROWSER_TYPE_HTMLUNIT)) {
                DesiredCapabilities capabilities = getDesiredCapabilities(browser);
                capabilities.setJavascriptEnabled(PropertyHelper.getHtmlUnitEnableJavascript());

                webDriver = new HtmlUnitDriver(capabilities);
            }
        }

        // default in PropertyHelper is 0.  Set this options only if they were explicitly specified (.properties or 
        // in the environment
        long scriptTimeout = PropertyHelper.getScriptTimeout();
        long implicitlyWait = PropertyHelper.getImplicitlyWait();
        long pageLoadTimeout = PropertyHelper.getPageLoadTimeout();
        if (scriptTimeout > 0)
            webDriver.manage().timeouts().setScriptTimeout(scriptTimeout, TimeUnit.MILLISECONDS);
        if (implicitlyWait > 0)
            webDriver.manage().timeouts().implicitlyWait(implicitlyWait, TimeUnit.MILLISECONDS);
        if (pageLoadTimeout > 0)
            webDriver.manage().timeouts().pageLoadTimeout(pageLoadTimeout, TimeUnit.MILLISECONDS);
    }
    return webDriver;
}

From source file:org.wisdom.test.parents.WisdomFluentLeniumTest.java

License:Apache License

@Override
public WebDriver getDefaultDriver() {
    String browser = System.getProperty("fluentlenium.browser");
    LOGGER.debug("Selecting Selenium Browser using " + browser);
    if (browser == null) {
        LOGGER.debug("Using default HTML Unit Driver");
        return new HtmlUnitDriver();
    }//from  w  ww.  java  2  s  .c  o  m

    if ("chrome".equalsIgnoreCase(browser)) {
        LOGGER.debug("Using Chrome");
        return new ChromeDriver();
    }

    if ("firefox".equalsIgnoreCase(browser)) {
        LOGGER.debug("Using Firefox");
        return new FirefoxDriver();
    }

    if ("ie".equalsIgnoreCase(browser) || "internetexplorer".equalsIgnoreCase(browser)) {
        LOGGER.debug("Using Internet Explorer");
        return new InternetExplorerDriver();
    }

    if ("safari".equalsIgnoreCase(browser)) {
        LOGGER.debug("Using Safari");
        return new SafariDriver();
    }

    throw new IllegalArgumentException("Unknown browser : " + browser);
}

From source file:renascere.Renascere.java

License:Open Source License

/**
 * @Description Method that opens a specified browser
 *//*from   w ww .  j av a  2  s  .  c om*/
static WebDriver openABrowser(browser bBrowserName) {
    WebDriver driver = null;
    String sDriverName = null;
    DesiredCapabilities DesireCaps = new DesiredCapabilities();

    try {
        //Creating browser instance
        switch (bBrowserName) {
        case FIREFOX:
            //Initializing Driver
            FirefoxProfile browserProfile = new FirefoxProfile();

            //Adding following preferences to download files
            browserProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream");
            browserProfile.setPreference("browser.download.folderList", 2);
            browserProfile.setPreference("browser.download.dir", Vars.os_PathOut);
            browserProfile.setPreference("browser.download.manager.alertOnEXEOpen", false);
            browserProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
                    "application/msword, application/csv, "
                            + "application/ris, text/csv, image/png, application/pdf, text/html, "
                            + "text/plain, application/zip, application/x-zip, application/x-zip-compressed, "
                            + "application/download, application/octet-stream");
            browserProfile.setPreference("browser.download.manager.showWhenStarting", false);
            browserProfile.setPreference("browser.download.manager.focusWhenStarting", false);
            browserProfile.setPreference("browser.download.useDownloadDir", true);
            browserProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
            browserProfile.setPreference("browser.download.manager.alertOnEXEOpen", false);
            browserProfile.setPreference("browser.download.manager.closeWhenDone", true);
            browserProfile.setPreference("browser.download.manager.showAlertOnComplete", false);
            browserProfile.setPreference("browser.download.manager.useWindow", false);
            browserProfile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting",
                    false);
            browserProfile.setPreference("pdfjs.disabled", true);
            browserProfile.setPreference("browser.download.manager.openDelay", 100000);
            browserProfile.setPreference("browser.download.animateNotifications", false);
            driver = new FirefoxDriver(browserProfile);
            break;
        case CHROME:
            //Determine driver to be used
            sDriverName = Vars.os_Name.toLowerCase().contains("win") ? "chromedriver-win.exe"
                    : (Vars.os_Name.toLowerCase().contains("mac") ? "chromedriver-mac" : "chromedriver-lnx");

            //Initializing Driver
            System.setProperty("webdriver.chrome.driver", Vars.os_PathRef + sDriverName);
            DesireCaps = DesiredCapabilities.chrome();
            driver = new ChromeDriver(DesireCaps);
            break;
        case IE:
            //Determine driver to be used
            System.setProperty("webdriver.ie.driver", Vars.os_PathRef + "IEDriverServer-win.exe");
            DesireCaps = Vars.os_Name.toLowerCase().contains("win") ? DesiredCapabilities.internetExplorer()
                    : null;
            if (DesireCaps == null) {
                throw new Exception("Invalid OS for browser.");
            }

            //Create instance
            driver = new InternetExplorerDriver(DesireCaps);
            break;
        case OPERA:
            //Determine driver to be used
            sDriverName = Vars.os_Name.toLowerCase().contains("win") ? "operadriver-win.exe"
                    : (Vars.os_Name.toLowerCase().contains("mac") ? "operadriver-mac" : "operadriver-lnx");

            //Initializing Driver
            System.setProperty("webdriver.chrome.driver", Vars.os_PathRef + sDriverName);
            driver = new ChromeDriver();
            break;
        case SAFARI:
            //Initializing Driver
            driver = new SafariDriver();
            break;
        case PHANTOMJS:
            //Determine driver to be used
            sDriverName = Vars.os_Name.toLowerCase().contains("win") ? "phantomjs-win.exe"
                    : (Vars.os_Name.toLowerCase().contains("mac") ? "phantomjs-mac" : "phantomjs-lnx");

            //Initializing Driver
            DesireCaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
                    Vars.os_PathRef + sDriverName);
            driver = new PhantomJSDriver();
            break;
        default:
            throw new Exception("Unsupported browser.");
        }

        //Getting additional browser information
        Vars.ts_BHandler = driver.getWindowHandle();

    } catch (Exception e) {
        frmError("creating a browser instance (" + bBrowserName + ")", e.getMessage(), severity.HIGH);
    }
    return driver;
}