public static HttpCommandExecutor getProxyExecutor(URL url, Properties prop) { prop = decrypt(prop); String proxyHost = prop.getProperty("proxyHost"); int proxyPort = Integer.valueOf(prop.getProperty("proxyPort")); String proxyUserDomain = prop.getProperty("proxyUserDomain"); String proxyUser = prop.getProperty("proxyUser"); String proxyPassword = prop.getProperty("proxyPassword"); HttpClientBuilder builder = HttpClientBuilder.create(); HttpHost proxy = new HttpHost(proxyHost, proxyPort); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUser, proxyPassword, getWorkstation(), proxyUserDomain)); if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) { credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())), new UsernamePasswordCredentials(proxyUser, proxyPassword)); } builder.setProxy(proxy); builder.setDefaultCredentialsProvider(credsProvider); HttpClient.Factory factory = new SimpleHttpClientFactory(builder); return new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory); }
/** * @param executor is an instance of {@link org.openqa.selenium.remote.HttpCommandExecutor} * or class that extends it. Default commands or another vendor-specific * commands may be specified there. * @param capabilities take a look * at {@link org.openqa.selenium.Capabilities} * @param converterClazz is an instance of a class that extends * {@link org.openqa.selenium.remote.internal.JsonToWebElementConverter}. It converts * JSON response to an instance of * {@link org.openqa.selenium.WebElement} */ protected AppiumDriver(HttpCommandExecutor executor, Capabilities capabilities, Class<? extends JsonToWebElementConverter> converterClazz) { super(executor, capabilities); this.executeMethod = new AppiumExecutionMethod(this); locationContext = new RemoteLocationContext(executeMethod); super.setErrorHandler(errorHandler); this.remoteAddress = executor.getAddressOfRemoteServer(); try { Constructor<? extends JsonToWebElementConverter> constructor = converterClazz.getConstructor(RemoteWebDriver.class); this.setElementConverter(constructor.newInstance(this)); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new RuntimeException(e); } }
private URL getSesionNodeUrl(RemoteWebDriver remoteDriver) { URL hostFound = null; try { HttpCommandExecutor sessionExcuter = (HttpCommandExecutor) remoteDriver.getCommandExecutor(); HttpHost host = new HttpHost(sessionExcuter.getAddressOfRemoteServer().getHost(), sessionExcuter.getAddressOfRemoteServer().getPort()); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", new URL("http://" + sessionExcuter.getAddressOfRemoteServer().getHost() + ":" + sessionExcuter.getAddressOfRemoteServer().getPort() + "/grid/api/testsession?session=" + remoteDriver.getSessionId()).toExternalForm()); HttpResponse response = new DefaultHttpClient().execute(host, request); URL myURL = new URL(new JSONObject(EntityUtils.toString(response.getEntity())).getString("proxyId")); if ((myURL.getHost() != null) && (myURL.getPort() != -1)) { hostFound = myURL; } } catch (Exception e) { } return hostFound; }
public WebDriverEx createWebDriver(DriverService driverService, DesiredCapabilities desiredCapabilities, SiteConfig siteConfig, DriverConfig driverConfig) throws IOException { driverService.start(); //自定义HttpClientFactory用于设置命令超时时间 ApacheHttpClient.Factory httpClientFactory = createHttpClientFactory(siteConfig, driverConfig); HttpCommandExecutor httpCommandExecutor = new HttpCommandExecutor( ImmutableMap.<String, CommandInfo>of(), driverService.getUrl(), httpClientFactory); WebDriverEx webDriver = new WebDriverEx(httpCommandExecutor, desiredCapabilities); webDriver.setDriverService(driverService); webDriver.setCreatedTime(new Date()); webDriver.manage().timeouts().implicitlyWait(driverConfig.getImplicitlyWait(), TimeUnit.MILLISECONDS); webDriver.manage().timeouts().pageLoadTimeout(driverConfig.getPageLoadTimeout(), TimeUnit.MILLISECONDS); webDriver.manage().timeouts().setScriptTimeout(driverConfig.getScriptTimeout(), TimeUnit.MILLISECONDS); return webDriver; }
/** * A helper method that enriches a {@link RemoteWebDriver} instance with the ability to route all browser * interaction requests directly to the node on which the session was created and route only the session termination * request to the hub. * * @param driver - A {@link RemoteWebDriver} instance. * @param hub - A {@link Host} object that represents the Hub information. * @return - A {@link RemoteWebDriver} instance that is enriched with the ability to route all browser interactions * directly to the node. */ public static RemoteWebDriver enrichRemoteWebDriverToInteractDirectlyWithNode(RemoteWebDriver driver, Host hub) { if (hub == null) { return driver; } try { CommandExecutor grid = driver.getCommandExecutor(); String sessionId = driver.getSessionId().toString(); GridApiAssistant assistant = new GridApiAssistant(hub); Host nodeHost = assistant.getNodeDetailsForSession(sessionId); URL url = new URL(String.format("http://%s:%d/wd/hub", nodeHost.getIpAddress(), nodeHost.getPort())); CommandExecutor node = new HttpCommandExecutor(url); CommandCodec commandCodec = getCodec(grid, "commandCodec"); ResponseCodec responseCodec = getCodec(grid, "responseCodec"); setCodec(node, commandCodec, "commandCodec"); setCodec(node, responseCodec, "responseCodec"); appendListenerToWebDriver(driver, grid, node); LOG.info("Traffic will now be routed directly to the node."); LOG.warning(constructWarningMessage(hub)); } catch (Exception e) { //Gobble exceptions LOG.warning("Unable to enrich the RemoteWebDriver instance. Root cause :" + e.getMessage() + ". Returning back the original instance that was passed, as is."); } return driver; }
private static Host getHubInfo(RemoteWebDriver driver) { Host hub = null; CommandExecutor executor = driver.getCommandExecutor(); if (executor instanceof HttpCommandExecutor) { URL url = ((HttpCommandExecutor) executor).getAddressOfRemoteServer(); hub = new Host(url.getHost(), Integer.toString(url.getPort())); } return hub; }
/** * Patch for * https://github.com/CognizantQAHub/Cognizant-Intelligent-Test-Scripter/issues/7 * Based on * https://github.com/mozilla/geckodriver/issues/759#issuecomment-308522851 * * @param fDriver FirefoxDriver */ private static void addGeckoDriverAddon(FirefoxDriver fDriver) { if (SystemDefaults.getClassesFromJar.get() && SystemDefaults.debugMode.get()) { if (FilePath.getFireFoxAddOnPath().exists()) { HttpCommandExecutor ce = (HttpCommandExecutor) fDriver.getCommandExecutor(); String url = ce.getAddressOfRemoteServer() + "/session/" + fDriver.getSessionId() + "/moz/addon/install"; addGeckoDriverAddon(FilePath.getFireFoxAddOnPath(), url); } } }
/** * Returns an {@link URL} to a Selenium grid (e.g. SauceLabs) that contains basic authentication for access * * @return {@link URL} to Selenium grid augmented with credentials * @throws MalformedURLException */ public static HttpCommandExecutor createGridExecutor(ProxyConfigurationDto proxyConfig, URL gridUrl, String gridUsername, String gridPassword) throws MalformedURLException { // create a configuration for accessing target site via proxy (if a proxy is defined) // the proxy and the destination site will have different or no credentials for accessing them // so we need to create different authentication scopes and link them with the credentials BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider(); // create credentials for proxy access if (proxyConfig != null // && !StringUtils.isEmpty(proxyConfig.getUsername()) // && !StringUtils.isEmpty(proxyConfig.getPassword())) { AuthScope proxyAuth = new AuthScope(proxyConfig.getHost(), Integer.valueOf(proxyConfig.getPort())); Credentials proxyCredentials = new UsernamePasswordCredentials(proxyConfig.getUsername(), proxyConfig.getPassword()); basicCredentialsProvider.setCredentials(proxyAuth, proxyCredentials); } // create credentials for target website AuthScope gridAuth = new AuthScope(gridUrl.getHost(), gridUrl.getPort()); if (!StringUtils.isEmpty(gridUsername)) { Credentials gridCredentials = new UsernamePasswordCredentials(gridUsername, gridPassword); basicCredentialsProvider.setCredentials(gridAuth, gridCredentials); } // now create a http client, set the custom proxy and inject the credentials HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultCredentialsProvider(basicCredentialsProvider); if (proxyConfig != null) clientBuilder.setProxy(new HttpHost(proxyConfig.getHost(), Integer.valueOf(proxyConfig.getPort()))); CloseableHttpClient httpClient = clientBuilder.build(); Map<String, CommandInfo> additionalCommands = new HashMap<String, CommandInfo>(); // just a dummy // this command executor will do the credential magic for us. both proxy and target site credentials return new HttpCommandExecutor(additionalCommands, gridUrl, new ProxyHttpClient(httpClient)); }
/** * Connect to selenium. * * @throws MalformedURLException */ @Before(order = ORDER_10, value = {"@mobile,@web"}) public void seleniumSetup() throws MalformedURLException { String grid = System.getProperty("SELENIUM_GRID"); if (grid == null) { fail("Selenium grid not available"); } String b = ThreadProperty.get("browser"); if ("".equals(b)) { fail("Non available browsers"); } String browser = b.split("_")[0]; String version = b.split("_")[1]; commonspec.setBrowserName(browser); commonspec.getLogger().debug("Setting up selenium for {}", browser); DesiredCapabilities capabilities = null; switch (browser.toLowerCase()) { case "chrome": ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.addArguments("--no-sandbox"); chromeOptions.addArguments("--ignore-certificate-errors"); capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); break; case "firefox": capabilities = DesiredCapabilities.firefox(); break; case "phantomjs": capabilities = DesiredCapabilities.phantomjs(); break; case "iphone": case "safari": capabilities = DesiredCapabilities.iphone(); capabilities.setCapability("platformName", "iOS"); capabilities.setCapability("platformVersion", "8.1"); capabilities.setCapability("deviceName", "iPhone Simulator"); break; case "android": capabilities = DesiredCapabilities.android(); capabilities.setCapability("platformName", "Android"); capabilities.setCapability("platformVersion", "6.0"); capabilities.setCapability("deviceName", "Android Emulator"); capabilities.setCapability("app", "Browser"); break; default: commonspec.getLogger().error("Unknown browser: " + browser); throw new SeleniumException("Unknown browser: " + browser); } capabilities.setVersion(version); grid = "http://" + grid + "/wd/hub"; HttpClient.Factory factory = new ApacheHttpClient.Factory(new HttpClientFactory(60000, 60000)); HttpCommandExecutor executor = new HttpCommandExecutor(new HashMap<String, CommandInfo>(), new URL(grid), factory); commonspec.setDriver(new RemoteWebDriver(executor, capabilities)); commonspec.getDriver().manage().timeouts().pageLoadTimeout(PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS); commonspec.getDriver().manage().timeouts().implicitlyWait(IMPLICITLY_WAIT, TimeUnit.SECONDS); commonspec.getDriver().manage().timeouts().setScriptTimeout(SCRIPT_TIMEOUT, TimeUnit.SECONDS); commonspec.getDriver().manage().deleteAllCookies(); if (capabilities.getCapability("deviceName") == null) { commonspec.getDriver().manage().window().setSize(new Dimension(1440, 900)); } commonspec.getDriver().manage().window().maximize(); }
protected WebDriver createRemoteWebDriver(DesiredCapabilities desiredCapabilities, URL remoteUrl) { HttpCommandExecutor httpCommandExecutor = new HttpCommandExecutor(remoteUrl); setRemoteWebDriverProxy(httpCommandExecutor); return new Augmenter().augment(new RemoteWebDriver(httpCommandExecutor, desiredCapabilities)); }
/** * @param executor is an instance of {@link org.openqa.selenium.remote.HttpCommandExecutor} * or class that extends it. Default commands or another vendor-specific * commands may be specified there. * @param capabilities take a look * at {@link org.openqa.selenium.Capabilities} */ public AndroidDriver(HttpCommandExecutor executor, Capabilities capabilities) { super(executor, capabilities, JsonToAndroidElementConverter.class); }
/** * @param executor is an instance of {@link org.openqa.selenium.remote.HttpCommandExecutor} * or class that extends it. Default commands or another vendor-specific * commands may be specified there. * @param capabilities take a look * at {@link org.openqa.selenium.Capabilities} */ public IOSDriver(HttpCommandExecutor executor, Capabilities capabilities) { super(executor, capabilities, JsonToIOSElementConverter.class); }
/** * Creates a new PhantomJSDriver instance using the given HttpCommandExecutor. * * @param executor The command executor to use * @param desiredCapabilities The capabilities required from PhantomJS/GhostDriver. */ public PhantomJSDriver(HttpCommandExecutor executor, Capabilities desiredCapabilities) { super(new org.openqa.selenium.phantomjs.PhantomJSDriver(executor, desiredCapabilities)); }