cn.hxh.springside.test.functional.WebDriverFactory.java Source code

Java tutorial

Introduction

Here is the source code for cn.hxh.springside.test.functional.WebDriverFactory.java

Source

/**
 * Copyright (c) 2005-2011 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: Fixtures.java 1593 2011-05-11 10:37:12Z calvinxiu $
 */
package cn.hxh.springside.test.functional;

import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.springframework.util.Assert;
import cn.hxh.springside.utils.ExceptionUtils;

/**
 * WebDriver, ??firefox,ieremote?driver.
 * 
 * @author calvin
 */
public class WebDriverFactory {
    public enum BrowserType {
        firefox, ie, remote
    }

    /**
     * ?driverName??WebDriver.
     * 
     * ????Windows, IE?XWindows, ?remote dirverWindows.
     * drivernameremote:192.168.0.2:3000:firefox, ??http://192.168.0.2:3000/wd?selnium remote?.
     * @throws MalformedURLException 
     */
    public static WebDriver createDriver(String driverName) {
        WebDriver driver = null;

        if (BrowserType.firefox.name().equals(driverName)) {
            driver = new FirefoxDriver();
        } else if (BrowserType.ie.name().equals(driverName)) {
            driver = new InternetExplorerDriver();
        } else if (driverName.startsWith(BrowserType.remote.name())) {
            String[] params = driverName.split(":");
            Assert.isTrue(params.length == 4,
                    "Remote driver is not right, accept format is \"remote:localhost:3000:firefox\", but the input is\""
                            + driverName + "\"");

            String remoteHost = params[1];
            String remotePort = params[2];
            String driverType = params[3];
            DesiredCapabilities cap = null;

            if (BrowserType.firefox.name().equals(driverType)) {
                cap = DesiredCapabilities.firefox();
            } else if (BrowserType.ie.name().equals(driverType)) {
                cap = DesiredCapabilities.internetExplorer();
            }

            try {
                driver = new RemoteWebDriver(new URL("http://" + remoteHost + ":" + remotePort + "/wd"), cap);
            } catch (MalformedURLException e) {
                throw ExceptionUtils.unchecked(e);
            }
        }

        Assert.notNull(driver, "Driver could be found by name:" + driverName);

        return driver;
    }
}