How to use getPort method of org.cerberus.engine.entity.Selenium class

Best Cerberus-source code snippet using org.cerberus.engine.entity.Selenium.getPort

Source:RobotServerService.java Github

copy

Full Screen

...218 */219 String hubUrl = StringUtil.cleanHostURL(RobotServerService.getBaseUrl(StringUtil.formatURLCredential(220 tCExecution.getSession().getHostUser(),221 tCExecution.getSession().getHostPassword(), session.getHost()),222 session.getPort())) + "/wd/hub";223 LOG.debug("Hub URL :" + hubUrl);224 URL url = new URL(hubUrl);225 HttpCommandExecutor executor = null;226 boolean isProxy = proxyService.useProxy(hubUrl, system);227// HttpClientBuilder builder = HttpClientBuilder.create();228 Factory factory = new OkHttpClient.Factory();229 // Timeout Management230 int robotTimeout = parameterService.getParameterIntegerByKey("cerberus_robot_timeout", system, 60000);231 Duration rbtTimeOut = Duration.ofMillis(robotTimeout);232 factory.builder().connectionTimeout(rbtTimeOut);233// RequestConfig.Builder requestBuilder = RequestConfig.custom();234// requestBuilder = requestBuilder.setConnectTimeout(robotTimeout);235// requestBuilder = requestBuilder.setConnectionRequestTimeout(robotTimeout);236// requestBuilder = requestBuilder.setSocketTimeout(robotTimeout);237// builder.setDefaultRequestConfig(requestBuilder.build());238 if (isProxy) {239 // Proxy Management240 String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", system, DEFAULT_PROXY_HOST);241 int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", system, DEFAULT_PROXY_PORT);242// HttpHost proxy = new HttpHost(proxyHost, proxyPort);243// SocketAddress sa = new SocketAddress() {244// }245 java.net.Proxy myproxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));246// Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);247// builder.setProxy(proxy);248 if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system, DEFAULT_PROXYAUTHENT_ACTIVATE)) {249 String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", system, DEFAULT_PROXYAUTHENT_USER);250 String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", system, DEFAULT_PROXYAUTHENT_PASSWORD);251 Authenticator proxyAuthenticator = new Authenticator() {252 public Request authenticate(Route route, Response response) throws IOException {253 String credential = Credentials.basic(proxyUser, proxyPassword);254 return response.request().newBuilder()255 .header("Proxy-Authorization", credential)256 .build();257 }258 };259 factory.builder().proxy(myproxy);260// CredentialsProvider credsProvider = new BasicCredentialsProvider();261//262// credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));263//264// if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {265// credsProvider.setCredentials(266// new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())),267// new UsernamePasswordCredentials(tCExecution.getSession().getHostUser(), tCExecution.getSession().getHostPassword())268// );269// }270// builder.setDefaultCredentialsProvider(credsProvider);271 } else {272 factory.builder().proxy(myproxy);273 }274 } else {275 factory.builder().proxy(java.net.Proxy.NO_PROXY);276 }277 executor = new HttpCommandExecutor(new HashMap<>(), url, factory);278// executor = new HttpCommandExecutor(new HashMap<>(), url);279 /**280 * SetUp Driver281 */282 LOG.debug("Set Driver");283 WebDriver driver = null;284 AppiumDriver appiumDriver = null;285 switch (tCExecution.getApplicationObj().getType().toUpperCase()) {286 case Application.TYPE_GUI:287 if (caps.getPlatform() != null && caps.getPlatform().is(Platform.ANDROID)) {288 // Appium does not support connection from HTTPCommandExecutor. When connecting from Executor, it stops to work after a couple of instructions.289 appiumDriver = new AndroidDriver(url, caps);290 driver = (WebDriver) appiumDriver;291 } else if (caps.getPlatform() != null && (caps.getPlatform().is(Platform.IOS) || caps.getPlatform().is(Platform.MAC))) {292 appiumDriver = new IOSDriver(url, caps);293 driver = (WebDriver) appiumDriver;294 } else {295 driver = new RemoteWebDriver(executor, caps);296 }297 tCExecution.setRobotSessionID(getSession(driver, tCExecution.getRobotProvider()));298 break;299 case Application.TYPE_APK:300 // add a lock on app path this part of code, because we can't install 2 apk with the same name simultaneously301 String appUrl = null;302 if (caps.getCapability("app") != null) {303 appUrl = caps.getCapability("app").toString();304 }305 int toto = totocpt++;306 if (appUrl != null) { // FIX : appium can't install 2 apk simultaneously, so implement a litle latency between execution307 synchronized (this) {308 // with appium 1.7.2, we can't install 2 fresh apk simultaneously. Appium have to prepare the apk (transformation) on the first execution before (see this topic https://discuss.appium.io/t/execute-2-android-test-simultaneously-problem-during-install-apk/22030)309 // provoque a latency if first test is already running and apk don't finish to be prepared310 if (apkAlreadyPrepare.containsKey(appUrl) && !apkAlreadyPrepare.get(appUrl)) {311 Thread.sleep(10000);312 } else {313 apkAlreadyPrepare.put(appUrl, false);314 }315 }316 }317 appiumDriver = new AndroidDriver(url, caps);318 if (apkAlreadyPrepare.containsKey(appUrl)) {319 apkAlreadyPrepare.put(appUrl, true);320 }321 driver = (WebDriver) appiumDriver;322 tCExecution.setRobotSessionID(getSession(driver, tCExecution.getRobotProvider()));323 break;324 case Application.TYPE_IPA:325 appiumDriver = new IOSDriver(url, caps);326 driver = (WebDriver) appiumDriver;327 tCExecution.setRobotSessionID(getSession(driver, tCExecution.getRobotProvider()));328 break;329 case Application.TYPE_FAT:330 /**331 * Check sikuli extension is reachable332 */333 if (!sikuliService.isSikuliServerReachable(session)) {334 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SIKULI_COULDNOTCONNECT);335 mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));336 mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));337 throw new CerberusException(mes);338 }339 /**340 * If CountryEnvParameter IP is set, open the App341 */342 if (!tCExecution.getCountryEnvironmentParameters().getIp().isEmpty()) {343 sikuliService.doSikuliActionOpenApp(session, tCExecution.getCountryEnvironmentParameters().getIp());344 }345 break;346 }347 /**348 * We record Server Side Caps.349 */350 if (driver != null) {351 try {352 // Init additionalFinalCapabilities and set it from real caps.353 List<RobotCapability> serverCapabilities = new ArrayList<>();354 for (Map.Entry cap : ((RemoteWebDriver) driver).getCapabilities().asMap().entrySet()) {355 serverCapabilities.add(factoryRobotCapability.create(0, "", cap.getKey().toString(), cap.getValue().toString()));356 }357 tCExecution.addFileList(recorderService.recordServerCapabilities(tCExecution, serverCapabilities));358 } catch (Exception ex) {359 LOG.error("Exception Saving Server Robot Caps " + tCExecution.getId(), ex);360 }361 }362 /**363 * Defining the timeout at the driver level. Only in case of not364 * Appium Driver (see365 * https://github.com/vertigo17/Cerberus/issues/754)366 */367 if (driver != null && appiumDriver == null) {368 driver.manage().timeouts().pageLoadTimeout(cerberus_selenium_pageLoadTimeout, TimeUnit.MILLISECONDS);369 driver.manage().timeouts().implicitlyWait(cerberus_selenium_implicitlyWait, TimeUnit.MILLISECONDS);370 driver.manage().timeouts().setScriptTimeout(cerberus_selenium_setScriptTimeout, TimeUnit.MILLISECONDS);371 }372 tCExecution.getSession().setDriver(driver);373 tCExecution.getSession().setAppiumDriver(appiumDriver);374 /**375 * If Gui application, maximize window Get IP of Node in case of376 * remote Server. Maximize does not work for chrome browser We also377 * get the Real UserAgent from the browser.378 */379 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI)380 && !caps.getPlatform().equals(Platform.ANDROID) && !caps.getPlatform().equals(Platform.IOS)381 && !caps.getPlatform().equals(Platform.MAC)) {382 if (!caps.getBrowserName().equals(BrowserType.CHROME)) {383 driver.manage().window().maximize();384 }385 getIPOfNode(tCExecution);386 /**387 * If screenSize is defined, set the size of the screen.388 */389 String targetScreensize = getScreenSizeToUse(tCExecution.getTestCaseObj().getScreenSize(), tCExecution.getScreenSize());390 LOG.debug("Selenium resolution : " + targetScreensize);391 if (!tCExecution.getBrowser().equalsIgnoreCase(BrowserType.CHROME)) {392 // For chrome the resolution has already been defined at capabilities level.393 if ((!StringUtil.isNullOrEmpty(targetScreensize)) && targetScreensize.contains("*")) {394 Integer screenWidth = Integer.valueOf(targetScreensize.split("\\*")[0]);395 Integer screenLength = Integer.valueOf(targetScreensize.split("\\*")[1]);396 setScreenSize(driver, screenWidth, screenLength);397 LOG.debug("Selenium resolution Activated : " + screenWidth + "*" + screenLength);398 }399 }400 tCExecution.setScreenSize(getScreenSize(driver));401 tCExecution.setRobotDecli(tCExecution.getRobotDecli().replace("%SCREENSIZE%", tCExecution.getScreenSize()));402 String userAgent = (String) ((JavascriptExecutor) driver).executeScript("return navigator.userAgent;");403 tCExecution.setUserAgent(userAgent);404 }405 // unlock device if deviceLockUnlock is active406 if (tCExecution.getRobotExecutorObj() != null && appiumDriver != null && appiumDriver instanceof LocksDevice407 && "Y".equals(tCExecution.getRobotExecutorObj().getDeviceLockUnlock())) {408 ((LocksDevice) appiumDriver).unlockDevice();409 }410 tCExecution.getSession().setStarted(true);411 } catch (CerberusException exception) {412 LOG.error(exception.toString(), exception);413 throw new CerberusException(exception.getMessageError(), exception);414 } catch (MalformedURLException exception) {415 LOG.error(exception.toString(), exception);416 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_URL_MALFORMED);417 mes.setDescription(mes.getDescription().replace("%URL%", tCExecution.getSession().getHost() + ":" + tCExecution.getSession().getPort()));418 throw new CerberusException(mes, exception);419 } catch (UnreachableBrowserException exception) {420 LOG.warn("Could not connect to : " + tCExecution.getSeleniumIP() + ":" + tCExecution.getSeleniumPort());421// LOG.error("UnreachableBrowserException catched.", exception);422 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SELENIUM_COULDNOTCONNECT);423 mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));424 mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));425 mes.setDescription(mes.getDescription().replace("%ERROR%", exception.toString()));426 throw new CerberusException(mes, exception);427 } catch (Exception exception) {428 LOG.error(exception.toString(), exception);429 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);430 mes.setDescription(mes.getDescription().replace("%MES%", exception.toString()));431 this.stopRemoteProxy(tCExecution);432 throw new CerberusException(mes, exception);433 } finally {434 executionThreadPoolService.executeNextInQueueAsynchroneously(false);435 }436 }437 private String getSession(WebDriver driver, String robotProvider) {438 String session = "";439 switch (robotProvider) {440 case TestCaseExecution.ROBOTPROVIDER_BROWSERSTACK:441 session = ((RemoteWebDriver) driver).getSessionId().toString();442 break;443 case TestCaseExecution.ROBOTPROVIDER_KOBITON:444 session = ((RemoteWebDriver) driver).getCapabilities().getCapability("kobitonSessionId").toString();445 break;446 case TestCaseExecution.ROBOTPROVIDER_NONE:447 session = ((RemoteWebDriver) driver).getSessionId().toString();448 break;449 default:450 }451 return session;452 }453 private String guessRobotProvider(String host) {454 if (host.contains("browserstack")) {455 return TestCaseExecution.ROBOTPROVIDER_BROWSERSTACK;456 }457 if (host.contains("kobiton")) {458 return TestCaseExecution.ROBOTPROVIDER_KOBITON;459 }460 return TestCaseExecution.ROBOTPROVIDER_NONE;461 }462 /**463 * Set DesiredCapabilities464 *465 * @param tCExecution466 * @return467 * @throws CerberusException468 */469 private MutableCapabilities setCapabilities(TestCaseExecution tCExecution) throws CerberusException {470 /**471 * Instanciate DesiredCapabilities472 */473 MutableCapabilities caps = new MutableCapabilities();474 // In case browser is not defined at that level, we force it to firefox.475 if (StringUtil.isNullOrEmpty(tCExecution.getBrowser())) {476 tCExecution.setBrowser("firefox");477 }478 /**479 * Set Browser Capabilities480 */481 caps = this.setCapabilityBrowser(caps, tCExecution.getBrowser(), tCExecution);482 /**483 * Loop on RobotCapabilities to feed DesiredCapabilities Capability must484 * be String, Integer or Boolean485 */486 List<RobotCapability> additionalCapabilities = new ArrayList<>();487 if (tCExecution.getRobotObj() != null) {488 additionalCapabilities = tCExecution.getRobotObj().getCapabilitiesDecoded();489 }490 if (additionalCapabilities != null) {491 for (RobotCapability additionalCapability : additionalCapabilities) {492 LOG.debug("RobotCaps on Robot : " + additionalCapability.getRobot() + " caps : " + additionalCapability.getCapability() + " Value : " + additionalCapability.getValue());493 if ((caps.getCapability(additionalCapability.getCapability()) == null)494 || ((caps.getCapability(additionalCapability.getCapability()) != null) && (caps.getCapability(additionalCapability.getCapability()).toString().equals("")))) { // caps does not already exist so we can set it.495 if (StringUtil.isBoolean(additionalCapability.getValue())) {496 caps.setCapability(additionalCapability.getCapability(), StringUtil.parseBoolean(additionalCapability.getValue()));497 } else if (StringUtil.isInteger(additionalCapability.getValue())) {498 caps.setCapability(additionalCapability.getCapability(), Integer.valueOf(additionalCapability.getValue()));499 } else {500 caps.setCapability(additionalCapability.getCapability(), additionalCapability.getValue());501 }502 }503 }504 } else {505 additionalCapabilities = new ArrayList<>();506 }507 /**508 * Feed DesiredCapabilities with values get from Robot509 */510 if (!StringUtil.isNullOrEmpty(tCExecution.getPlatform())) {511 if ((caps.getCapability("platform") == null)512 || ((caps.getCapability("platform") != null) && (caps.getCapability("platform").toString().equals("ANY") || caps.getCapability("platform").toString().equals("")))) {513 caps.setCapability("platformName", tCExecution.getPlatform());514 }515 }516 if (!StringUtil.isNullOrEmpty(tCExecution.getVersion())) {517 if ((caps.getCapability("version") == null)518 || ((caps.getCapability("version") != null) && (caps.getCapability("version").toString().equals("")))) {519 caps.setCapability("version", tCExecution.getVersion());520 }521 }522 if (tCExecution.getRobotExecutorObj() != null) {523 // Setting deviceUdid and device name from executor.524 if (!StringUtil.isNullOrEmpty(tCExecution.getRobotExecutorObj().getDeviceUuid())) {525 if ((caps.getCapability("udid") == null)526 || ((caps.getCapability("udid") != null) && (caps.getCapability("udid").toString().equals("")))) {527 caps.setCapability("udid", tCExecution.getRobotExecutorObj().getDeviceUuid());528 }529 }530 if (!StringUtil.isNullOrEmpty(tCExecution.getRobotExecutorObj().getDeviceName())) {531 if ((caps.getCapability("deviceName") == null)532 || ((caps.getCapability("deviceName") != null) && (caps.getCapability("deviceName").toString().equals("")))) {533 caps.setCapability("deviceName", tCExecution.getRobotExecutorObj().getDeviceName());534 }535 }536 if (!StringUtil.isNullOrEmpty(tCExecution.getRobotExecutorObj().getDeviceName())) {537 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)) {538 if ((caps.getCapability("systemPort") == null)539 || ((caps.getCapability("systemPort") != null) && (caps.getCapability("systemPort").toString().equals("")))) {540 caps.setCapability("systemPort", tCExecution.getRobotExecutorObj().getDevicePort());541 }542 } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_IPA)) {543 if ((caps.getCapability("wdaLocalPort") == null)544 || ((caps.getCapability("wdaLocalPort") != null) && (caps.getCapability("wdaLocalPort").toString().equals("")))) {545 caps.setCapability("wdaLocalPort", tCExecution.getRobotExecutorObj().getDevicePort());546 }547 }548 }549 }550 /**551 * if application is a mobile one, then set the "app" capability to the552 * application binary path553 */554 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)555 || tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_IPA)) {556 // Set the app capability with the application path557 if (!StringUtil.isNullOrEmpty(tCExecution.getMyHost())) {558 if (isNotAlreadyDefined(caps, "app")) {559 caps.setCapability("app", tCExecution.getMyHost());560 }561 } else {562 if (isNotAlreadyDefined(caps, "app")) {563 caps.setCapability("app", tCExecution.getCountryEnvironmentParameters().getIp());564 }565 }566 if (!StringUtil.isNullOrEmpty(tCExecution.getCountryEnvironmentParameters().getMobileActivity()) && tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)) {567 if (isNotAlreadyDefined(caps, "appWaitActivity")) {568 caps.setCapability("appWaitActivity", tCExecution.getCountryEnvironmentParameters().getMobileActivity());569 }570 }571 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)) {572 if (isNotAlreadyDefined(caps, "automationName")) {573 caps.setCapability("automationName", "UIAutomator2"); // use UIAutomator2 by default574 }575 }576 }577 /**578 * We record Selenium log at the end of the execution.579 */580 switch (tCExecution.getRobotProvider()) {581 case TestCaseExecution.ROBOTPROVIDER_BROWSERSTACK:582 if (!StringUtil.isNullOrEmpty(tCExecution.getTag()) && isNotAlreadyDefined(caps, "build")) {583 caps.setCapability("build", tCExecution.getTag()); // use UIAutomator2 by default584 }585 if (isNotAlreadyDefined(caps, "project")) {586 caps.setCapability("project", tCExecution.getApplication());587 }588 if (isNotAlreadyDefined(caps, "name")) {589 String externalExeName = parameterService.getParameterStringByKey("cerberus_browserstack_defaultexename", tCExecution.getSystem(), "Exe : %EXEID%");590 externalExeName = externalExeName.replace("%EXEID%", String.valueOf(tCExecution.getId()));591 caps.setCapability("name", externalExeName);592 }593 if (tCExecution.getVerbose() >= 2) {594 if (isNotAlreadyDefined(caps, "browserstack.debug")) {595 caps.setCapability("browserstack.debug", true);596 }597 if (isNotAlreadyDefined(caps, "browserstack.console")) {598 caps.setCapability("browserstack.console", "warnings");599 }600 if (isNotAlreadyDefined(caps, "browserstack.networkLogs")) {601 caps.setCapability("browserstack.networkLogs", true);602 }603 }604 break;605 case TestCaseExecution.ROBOTPROVIDER_KOBITON:606 if (isNotAlreadyDefined(caps, "sessionName")) {607 String externalExeName = parameterService.getParameterStringByKey("cerberus_kobiton_defaultsessionname", tCExecution.getSystem(), "%EXEID% : %TEST% - %TESTCASE%");608 externalExeName = externalExeName.replace("%EXEID%", String.valueOf(tCExecution.getId()));609 externalExeName = externalExeName.replace("%APPLI%", String.valueOf(tCExecution.getApplication()));610 externalExeName = externalExeName.replace("%TAG%", String.valueOf(tCExecution.getTag()));611 externalExeName = externalExeName.replace("%TEST%", String.valueOf(tCExecution.getTest()));612 externalExeName = externalExeName.replace("%TESTCASE%", String.valueOf(tCExecution.getTestCase()));613 externalExeName = externalExeName.replace("%TESTCASEDESC%", String.valueOf(tCExecution.getTestCaseObj().getDescription()));614 caps.setCapability("sessionName", externalExeName);615 }616 if (isNotAlreadyDefined(caps, "sessionDescription")) {617 String externalExeName = parameterService.getParameterStringByKey("cerberus_kobiton_defaultsessiondescription", tCExecution.getSystem(), "%TESTCASEDESC%");618 externalExeName = externalExeName.replace("%EXEID%", String.valueOf(tCExecution.getId()));619 externalExeName = externalExeName.replace("%APPLI%", String.valueOf(tCExecution.getApplication()));620 externalExeName = externalExeName.replace("%TAG%", String.valueOf(tCExecution.getTag()));621 externalExeName = externalExeName.replace("%TEST%", String.valueOf(tCExecution.getTest()));622 externalExeName = externalExeName.replace("%TESTCASE%", String.valueOf(tCExecution.getTestCase()));623 externalExeName = externalExeName.replace("%TESTCASEDESC%", String.valueOf(tCExecution.getTestCaseObj().getDescription()));624 caps.setCapability("sessionDescription", externalExeName);625 }626 if (isNotAlreadyDefined(caps, "deviceGroup")) {627 caps.setCapability("deviceGroup", "KOBITON"); // use UIAutomator2 by default628 }629 break;630 case TestCaseExecution.ROBOTPROVIDER_NONE:631 break;632 default:633 }634 return caps;635 }636 private boolean isNotAlreadyDefined(MutableCapabilities caps, String capability) {637 return ((caps.getCapability(capability) == null)638 || ((caps.getCapability(capability) != null) && (caps.getCapability(capability).toString().equals(""))));639 }640 /**641 * Instanciate DesiredCapabilities regarding the browser642 *643 * @param capabilities644 * @param browser645 * @param tCExecution646 * @return647 * @throws CerberusException648 */649 private MutableCapabilities setCapabilityBrowser(MutableCapabilities capabilities, String browser, TestCaseExecution tCExecution) throws CerberusException {650 try {651 if (browser.equalsIgnoreCase("firefox")) {652 FirefoxOptions options = new FirefoxOptions();653// capabilities = DesiredCapabilities.firefox();654 FirefoxProfile profile = new FirefoxProfile();655 profile.setPreference("app.update.enabled", false);656 try {657 Invariant invariant = invariantService.convert(invariantService.readByKey("COUNTRY", tCExecution.getCountry()));658 if (invariant.getGp2() == null) {659 LOG.warn("Country selected (" + tCExecution.getCountry() + ") has no value of GP2 in Invariant table, default language set to English (en)");660 profile.setPreference("intl.accept_languages", "en");661 } else {662 profile.setPreference("intl.accept_languages", invariant.getGp2());663 }664 } catch (CerberusException ex) {665 LOG.warn("Country selected (" + tCExecution.getCountry() + ") not in Invariant table, default language set to English (en)");666 profile.setPreference("intl.accept_languages", "en");667 }668 // Set UserAgent if testCaseUserAgent or robotUserAgent is defined669 String usedUserAgent = getUserAgentToUse(tCExecution.getTestCaseObj().getUserAgent(), tCExecution.getUserAgent());670 if (!StringUtil.isNullOrEmpty(usedUserAgent)) {671 profile.setPreference("general.useragent.override", usedUserAgent);672 }673// capabilities.setCapability(FirefoxDriver.PROFILE, profile);674 if (tCExecution.getVerbose() <= 0) {675 options.setHeadless(true);676 }677 // Add the WebDriver proxy capability.678 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {679 Proxy proxy = new Proxy();680 proxy.setHttpProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());681 proxy.setSslProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());682 options.setProxy(proxy);683 }684 options.setProfile(profile);685 return options;686// capabilities.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options);687 } else if (browser.equalsIgnoreCase("IE")) {688 InternetExplorerOptions options = new InternetExplorerOptions();689 // Add the WebDriver proxy capability.690 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {691 Proxy proxy = new Proxy();692 proxy.setHttpProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());693 proxy.setSslProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());694 options.setCapability("proxy", proxy);695 }696 return options;697// capabilities = DesiredCapabilities.internetExplorer();698 } else if (browser.equalsIgnoreCase("chrome")) {699 /**700 * Add custom capabilities701 */702 ChromeOptions options = new ChromeOptions();703// capabilities = DesiredCapabilities.chrome();704 // Maximize windows for chrome browser705 String targetScreensize = getScreenSizeToUse(tCExecution.getTestCaseObj().getScreenSize(), tCExecution.getScreenSize());706 if ((!StringUtil.isNullOrEmpty(targetScreensize)) && targetScreensize.contains("*")) {707 Integer screenWidth = Integer.valueOf(targetScreensize.split("\\*")[0]);708 Integer screenLength = Integer.valueOf(targetScreensize.split("\\*")[1]);709 String sizeOpts = "--window-size=" + screenWidth + "," + screenLength;710 options.addArguments(sizeOpts);711 LOG.debug("Selenium resolution (for Chrome) Activated : " + screenWidth + "*" + screenLength);712 }713 options.addArguments("start-maximized");714 if (tCExecution.getVerbose() <= 0) {715 options.addArguments("--headless");716 }717 // Set UserAgent if necessary718 String usedUserAgent = getUserAgentToUse(tCExecution.getTestCaseObj().getUserAgent(), tCExecution.getUserAgent());719 if (!StringUtil.isNullOrEmpty(usedUserAgent)) {720 options.addArguments("--user-agent=" + usedUserAgent);721 }722 // Add the WebDriver proxy capability.723 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {724 Proxy proxy = new Proxy();725 proxy.setHttpProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());726 proxy.setSslProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());727 options.setCapability("proxy", proxy);728 }729 return options;730// capabilities.setCapability(ChromeOptions.CAPABILITY, options);731// additionalCapabilities.add(factoryRobotCapability.create(0, "", ChromeOptions.CAPABILITY, options.toString()));732 } else if (browser.contains("android")) {733 // Launch the proxy with the settings specified in the robot options (executor)734 // since proxy Settings is out the Appium's scope, you must set it manually on your device735 // set the same port on device and robot736 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {737 this.startRemoteProxy(tCExecution);738 Proxy proxy = new Proxy();739 proxy.setHttpProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());740 proxy.setSslProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());741 }742 capabilities = DesiredCapabilities.android();743 } else if (browser.contains("ipad")) {744 capabilities = DesiredCapabilities.ipad();745 } else if (browser.contains("iphone")) {746 capabilities = DesiredCapabilities.iphone();747 } else if (browser.contains("safari")) {748 SafariOptions options = new SafariOptions();749 return options;750// capabilities = DesiredCapabilities.safari();751 } else {752 LOG.warn("Not supported Browser : " + browser);753 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);754 mes.setDescription(mes.getDescription().replace("%MES%", "Browser '" + browser + "' is not supported"));755 mes.setDescription("Not supported Browser : " + browser);756 throw new CerberusException(mes);757 }758 } catch (CerberusException ex) {759 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);760 mes.setDescription(mes.getDescription().replace("%MES%", "Failed to set capability on the browser '" + browser + "' due to " + ex.getMessageError().getDescription()));761 throw new CerberusException(mes);762 }763 return capabilities;764 }765 /**766 * This method determine which user agent to use.767 *768 * @param userAgentTestCase769 * @param userAgentRobot770 * @return String containing the userAgent to use771 */772 private String getUserAgentToUse(String userAgentTestCase, String userAgentRobot) {773 if (StringUtil.isNullOrEmpty(userAgentRobot) && StringUtil.isNullOrEmpty(userAgentTestCase)) {774 return "";775 } else {776 return StringUtil.isNullOrEmpty(userAgentTestCase) ? userAgentRobot : userAgentTestCase;777 }778 }779 /**780 * This method determine which screenSize to use.781 *782 * @param screenSizeTestCase783 * @param screenSizeRobot784 * @return String containing the screensize to use785 */786 private String getScreenSizeToUse(String screenSizeTestCase, String screenSizeRobot) {787 if (StringUtil.isNullOrEmpty(screenSizeRobot) && StringUtil.isNullOrEmpty(screenSizeTestCase)) {788 return "";789 } else {790 return StringUtil.isNullOrEmpty(screenSizeTestCase) ? screenSizeRobot : screenSizeTestCase;791 }792 }793 @Override794 public boolean stopServer(TestCaseExecution tce) {795 Session session = tce.getSession();796 if (session.isStarted()) {797 try {798 // Wait 2 sec till HAR is exported799 Thread.sleep(2000);800 } catch (InterruptedException ex) {801 LOG.error(ex.toString(), ex);802 }803 /**804 * We remove manually the package if it is defined.805 */806 if (session.getAppiumDriver() != null && tce.getCountryEnvironmentParameters() != null807 && !StringUtil.isNullOrEmpty(tce.getCountryEnvironmentParameters().getMobilePackage())) {808 session.getAppiumDriver().removeApp(tce.getCountryEnvironmentParameters().getMobilePackage());809 }810 /**811 * We lock device if deviceLockUnlock is active.812 */813 // 814 if (tce.getRobotExecutorObj() != null && session.getAppiumDriver() != null && session.getAppiumDriver() instanceof LocksDevice815 && "Y".equals(tce.getRobotExecutorObj().getDeviceLockUnlock())) {816 ((LocksDevice) session.getAppiumDriver()).lockDevice();817 }818 /**819 * We record Selenium log at the end of the execution.820 */821 switch (tce.getRobotProvider()) {822 case TestCaseExecution.ROBOTPROVIDER_BROWSERSTACK:823 try {824 tce.addFileList(recorderService.recordSeleniumLog(tce));825 } catch (Exception ex) {826 LOG.error("Exception Getting Selenium Logs " + tce.getId(), ex);827 }828// try {829// tce.addFileList(recorderService.recordBrowserstackSeleniumLog(tce));830// } catch (Exception ex) {831// LOG.error("Exception Getting Browserstack Selenium Logs " + tce.getId(), ex);832// }833// break;834 case TestCaseExecution.ROBOTPROVIDER_NONE:835 try {836 tce.addFileList(recorderService.recordSeleniumLog(tce));837 } catch (Exception ex) {838 LOG.error("Exception Getting Selenium Logs " + tce.getId(), ex);839 }840 break;841 default:842 }843 /**844 * We record Har log at the end of the execution.845 */846 switch (tce.getRobotProvider()) {847 case TestCaseExecution.ROBOTPROVIDER_BROWSERSTACK:848// try {849// String url = "http://api.bs.com/getHar?uuid=" + tce.getRobotSessionID();850// tce.addFileList(recorderService.recordBrowserstackHarLog(tce, url));851// } catch (Exception ex) {852// LOG.error("Exception Getting Browserstack HAR File " + tce.getId(), ex);853// }854 break;855 case TestCaseExecution.ROBOTPROVIDER_NONE:856 break;857 default:858 }859 try {860 // Get Har File when Cerberus Executor is activated.861 // If proxy started and parameter verbose >= 1 activated862 if ("Y".equals(tce.getRobotExecutorObj().getExecutorProxyActive())863 && tce.getVerbose() >= 1) {864 String url = "http://" + tce.getRobotExecutorObj().getHost() + ":" + tce.getRobotExecutorObj().getExecutorExtensionPort() + "/getHar?uuid=" + tce.getRemoteProxyUUID();865 LOG.debug("Url to get HAR : " + url);866 tce.addFileList(recorderService.recordHarLog(tce, url));867 LOG.debug("Retrieved Har file by calling : " + url);868 }869 } catch (Exception ex) {870 LOG.error("Exception Getting Har File from Cerberus Executor " + tce.getId(), ex);871 }872 /**873 * We Stop the Robot Session (Selenium or Appium).874 */875 LOG.info("Stop execution robot session");876 if (tce.getRobotProvider().equals(TestCaseExecution.ROBOTPROVIDER_KOBITON)) {877 // For Kobiton, we should first close Appium session.878 if (session.getAppiumDriver() != null) {879 session.getAppiumDriver().close();880 }881 if (session.getDriver() != null) {882 session.getDriver().quit();883 }884 } else {885 session.quit();886 }887 return true;888 }889 return false;890 }891 private static void getIPOfNode(TestCaseExecution tCExecution) {892 try {893 Session session = tCExecution.getSession();894 HttpCommandExecutor ce = (HttpCommandExecutor) ((RemoteWebDriver) session.getDriver()).getCommandExecutor();895 SessionId sessionId = ((RemoteWebDriver) session.getDriver()).getSessionId();896 String hostName = ce.getAddressOfRemoteServer().getHost();897 int port = ce.getAddressOfRemoteServer().getPort();898 HttpHost host = new HttpHost(hostName, port);899 HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();900 URL sessionURL = new URL(RobotServerService.getBaseUrl(session.getHost(), session.getPort()) + "/grid/api/testsession?session=" + sessionId);901 BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());902 HttpResponse response = client.execute(host, r);903 if (!response.getStatusLine().toString().contains("403")904 && !response.getEntity().getContentType().getValue().contains("text/html")) {905 InputStream contents = response.getEntity().getContent();906 StringWriter writer = new StringWriter();907 IOUtils.copy(contents, writer, "UTF8");908 JSONObject object = new JSONObject(writer.toString());909 if (object.has("proxyId")) {910 URL myURL = new URL(object.getString("proxyId"));911 if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {912 tCExecution.setRobotHost(myURL.getHost());913 tCExecution.setRobotPort(String.valueOf(myURL.getPort()));914 }915 } else {916 LOG.debug("'proxyId' json data not available from remote Selenium Server request : " + writer.toString());917 }918 }919 } catch (IOException | JSONException ex) {920 LOG.error(ex.toString(), ex);921 }922 }923 @Override924 public Capabilities getUsedCapabilities(Session session) {925 Capabilities caps = ((RemoteWebDriver) session.getDriver()).getCapabilities();926 return caps;927 }...

Full Screen

Full Screen

Source:SeleniumServerService.java Github

copy

Full Screen

...141 session.setCerberus_selenium_action_click_timeout(cerberus_selenium_action_click_timeout);142 session.setHost(tCExecution.getSeleniumIP());143 session.setHostUser(tCExecution.getSeleniumIPUser());144 session.setHostPassword(tCExecution.getSeleniumIPPassword());145 session.setPort(tCExecution.getPort());146 tCExecution.setSession(session);147 LOG.debug(logPrefix + "Session is set.");148 /**149 * SetUp Capabilities150 */151 LOG.debug(logPrefix + "Set Capabilities");152 DesiredCapabilities caps = this.setCapabilities(tCExecution);153 session.setDesiredCapabilities(caps);154 LOG.debug(logPrefix + "Set Capabilities - retreived");155 /**156 * SetUp Proxy157 */158 String hubUrl = StringUtil.cleanHostURL(159 SeleniumServerService.getBaseUrl(StringUtil.formatURLCredential(160 tCExecution.getSession().getHostUser(),161 tCExecution.getSession().getHostPassword()) + session.getHost(),162 session.getPort())) + "/wd/hub";163 LOG.debug(logPrefix + "Hub URL :" + hubUrl);164 URL url = new URL(hubUrl);165 HttpCommandExecutor executor = null;166 boolean isProxy = proxyService.useProxy(hubUrl, system);167 if (isProxy) {168 String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", system, DEFAULT_PROXY_HOST);169 int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", system, DEFAULT_PROXY_PORT);170 HttpClientBuilder builder = HttpClientBuilder.create();171 HttpHost proxy = new HttpHost(proxyHost, proxyPort);172 builder.setProxy(proxy);173 if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system, DEFAULT_PROXYAUTHENT_ACTIVATE)) {174 String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", system, DEFAULT_PROXYAUTHENT_USER);175 String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", system, DEFAULT_PROXYAUTHENT_PASSWORD);176 CredentialsProvider credsProvider = new BasicCredentialsProvider();177 credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));178 if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {179 credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())), new UsernamePasswordCredentials(url.getUserInfo()));180 }181 builder.setDefaultCredentialsProvider(credsProvider);182 }183 Factory factory = new MyHttpClientFactory(builder);184 executor = new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory);185 }186 /**187 * SetUp Driver188 */189 LOG.debug(logPrefix + "Set Driver");190 WebDriver driver = null;191 AppiumDriver appiumDriver = null;192 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI)) {193 if (caps.getPlatform().is(Platform.ANDROID)) {194 if (executor == null) {195 appiumDriver = new AndroidDriver(url, caps);196 } else {197 appiumDriver = new AndroidDriver(executor, caps);198 }199 driver = (WebDriver) appiumDriver;200 } else if (caps.getPlatform().is(Platform.MAC)) {201 if (executor == null) {202 appiumDriver = new IOSDriver(url, caps);203 } else {204 appiumDriver = new IOSDriver(executor, caps);205 }206 driver = (WebDriver) appiumDriver;207 } else // Any Other208 {209 if (executor == null) {210 driver = new RemoteWebDriver(url, caps);211 } else {212 driver = new RemoteWebDriver(executor, caps);213 }214 }215 } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)) {216 if (executor == null) {217 appiumDriver = new AndroidDriver(url, caps);218 } else {219 appiumDriver = new AndroidDriver(executor, caps);220 }221 driver = (WebDriver) appiumDriver;222 } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_IPA)) {223 if (executor == null) {224 appiumDriver = new IOSDriver(url, caps);225 } else {226 appiumDriver = new IOSDriver(executor, caps);227 }228 driver = (WebDriver) appiumDriver;229 } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_FAT)) {230 /**231 * Check sikuli extension is reachable232 */233 if (!sikuliService.isSikuliServerReachable(session)) {234 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SIKULI_COULDNOTCONNECT);235 mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));236 mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));237 throw new CerberusException(mes);238 }239 /**240 * If CountryEnvParameter IP is set, open the App241 */242 if (!tCExecution.getCountryEnvironmentParameters().getIp().isEmpty()) {243 sikuliService.doSikuliActionOpenApp(session, tCExecution.getCountryEnvironmentParameters().getIp());244 }245 }246 /**247 * Defining the timeout at the driver level. Only in case of not248 * Appium Driver (see249 * https://github.com/vertigo17/Cerberus/issues/754)250 */251 if (driver != null && appiumDriver == null) {252 driver.manage().timeouts().pageLoadTimeout(cerberus_selenium_pageLoadTimeout, TimeUnit.MILLISECONDS);253 driver.manage().timeouts().implicitlyWait(cerberus_selenium_implicitlyWait, TimeUnit.MILLISECONDS);254 driver.manage().timeouts().setScriptTimeout(cerberus_selenium_setScriptTimeout, TimeUnit.MILLISECONDS);255 }256 tCExecution.getSession().setDriver(driver);257 tCExecution.getSession().setAppiumDriver(appiumDriver);258 /**259 * If Gui application, maximize window Get IP of Node in case of260 * remote Server. Maximize does not work for chrome browser We also261 * get the Real UserAgent from the browser.262 */263 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI)264 && !caps.getPlatform().equals(Platform.ANDROID)) {265 if (!caps.getBrowserName().equals(BrowserType.CHROME)) {266 driver.manage().window().maximize();267 }268 getIPOfNode(tCExecution);269 /**270 * If screenSize is defined, set the size of the screen.271 */272 String targetScreensize = getScreenSizeToUse(tCExecution.getTestCaseObj().getScreenSize(), tCExecution.getScreenSize());273 LOG.debug("Selenium resolution : " + targetScreensize);274 if ((!StringUtil.isNullOrEmpty(targetScreensize)) && targetScreensize.contains("*")) {275 Integer screenWidth = Integer.valueOf(targetScreensize.split("\\*")[0]);276 Integer screenLength = Integer.valueOf(targetScreensize.split("\\*")[1]);277 setScreenSize(driver, screenWidth, screenLength);278 LOG.debug("Selenium resolution Activated : " + screenWidth + "*" + screenLength);279 }280 tCExecution.setScreenSize(getScreenSize(driver));281 tCExecution.setRobotDecli(tCExecution.getRobotDecli().replace("%SCREENSIZE%", tCExecution.getScreenSize()));282 String userAgent = (String) ((JavascriptExecutor) driver).executeScript("return navigator.userAgent;");283 tCExecution.setUserAgent(userAgent);284 }285 tCExecution.getSession().setStarted(true);286 } catch (CerberusException exception) {287 LOG.error(logPrefix + exception.toString(), exception);288 throw new CerberusException(exception.getMessageError());289 } catch (MalformedURLException exception) {290 LOG.error(logPrefix + exception.toString(), exception);291 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_URL_MALFORMED);292 mes.setDescription(mes.getDescription().replace("%URL%", tCExecution.getSession().getHost() + ":" + tCExecution.getSession().getPort()));293 throw new CerberusException(mes);294 } catch (UnreachableBrowserException exception) {295 LOG.error(logPrefix + exception.toString(), exception);296 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SELENIUM_COULDNOTCONNECT);297 mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));298 mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));299 mes.setDescription(mes.getDescription().replace("%ERROR%", exception.toString()));300 throw new CerberusException(mes);301 } catch (Exception exception) {302 LOG.error(logPrefix + exception.toString(), exception);303 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);304 mes.setDescription(mes.getDescription().replace("%MES%", exception.toString()));305 throw new CerberusException(mes);306 }307 }308 /**309 * Set DesiredCapabilities310 *311 * @param tCExecution312 * @return313 * @throws CerberusException314 */315 private DesiredCapabilities setCapabilities(TestCaseExecution tCExecution) throws CerberusException {316 /**317 * Instanciate DesiredCapabilities318 */319 DesiredCapabilities caps = new DesiredCapabilities();320 // In case browser is not defined at that level, we force it to firefox.321 if (StringUtil.isNullOrEmpty(tCExecution.getBrowser())) {322 tCExecution.setBrowser("firefox");323 }324 caps = this.setCapabilityBrowser(caps, tCExecution.getBrowser(), tCExecution);325 /**326 * Feed DesiredCapabilities with values get from Robot327 */328 if (!StringUtil.isNullOrEmpty(tCExecution.getPlatform())) {329 caps.setCapability("platform", tCExecution.getPlatform());330 }331 if (!StringUtil.isNullOrEmpty(tCExecution.getVersion())) {332 caps.setCapability("version", tCExecution.getVersion());333 }334 /**335 * Loop on RobotCapabilities to feed DesiredCapabilities Capability must336 * be String, Integer or Boolean337 */338 List<RobotCapability> additionalCapabilities = tCExecution.getCapabilities();339 if (additionalCapabilities != null) {340 for (RobotCapability additionalCapability : additionalCapabilities) {341 if (StringUtil.isBoolean(additionalCapability.getValue())) {342 caps.setCapability(additionalCapability.getCapability(), StringUtil.parseBoolean(additionalCapability.getValue()));343 } else if (StringUtil.isInteger(additionalCapability.getValue())) {344 caps.setCapability(additionalCapability.getCapability(), Integer.valueOf(additionalCapability.getValue()));345 } else {346 caps.setCapability(additionalCapability.getCapability(), additionalCapability.getValue());347 }348 }349 }350 /**351 * if application is a mobile one, then set the "app" capability to the352 * application binary path353 */354 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)355 || tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_IPA)) {356 // Set the app capability with the application path357 if (tCExecution.isManualURL()) {358 caps.setCapability("app", tCExecution.getMyHost());359 } else {360 caps.setCapability("app", tCExecution.getCountryEnvironmentParameters().getIp());361 }362 }363 return caps;364 }365 /**366 * Instanciate DesiredCapabilities regarding the browser367 *368 * @param capabilities369 * @param browser370 * @param tCExecution371 * @return372 * @throws CerberusException373 */374 private DesiredCapabilities setCapabilityBrowser(DesiredCapabilities capabilities, String browser, TestCaseExecution tCExecution) throws CerberusException {375 try {376 if (browser.equalsIgnoreCase("firefox")) {377 capabilities = DesiredCapabilities.firefox();378 FirefoxProfile profile = new FirefoxProfile();379 profile.setPreference("app.update.enabled", false);380 try {381 Invariant invariant = invariantService.convert(invariantService.readByKey("COUNTRY", tCExecution.getCountry()));382 if (invariant.getGp2() == null) {383 LOG.warn("Country selected (" + tCExecution.getCountry() + ") has no value of GP2 in Invariant table, default language set to English (en)");384 profile.setPreference("intl.accept_languages", "en");385 } else {386 profile.setPreference("intl.accept_languages", invariant.getGp2());387 }388 } catch (CerberusException ex) {389 LOG.warn("Country selected (" + tCExecution.getCountry() + ") not in Invariant table, default language set to English (en)");390 profile.setPreference("intl.accept_languages", "en");391 }392 // Set UserAgent if testCaseUserAgent or robotUserAgent is defined393 String usedUserAgent = getUserAgentToUse(tCExecution.getTestCaseObj().getUserAgent(), tCExecution.getUserAgent());394 if (!StringUtil.isNullOrEmpty(usedUserAgent)) {395 profile.setPreference("general.useragent.override", usedUserAgent);396 }397 capabilities.setCapability(FirefoxDriver.PROFILE, profile);398 } else if (browser.equalsIgnoreCase("IE")) {399 capabilities = DesiredCapabilities.internetExplorer();400 } else if (browser.equalsIgnoreCase("chrome")) {401 capabilities = DesiredCapabilities.chrome();402 /**403 * Add custom capabilities404 */405 ChromeOptions options = new ChromeOptions();406 // Maximize windows for chrome browser407 options.addArguments("--start-fullscreen");408 // Set UserAgent if necessary409 String usedUserAgent = getUserAgentToUse(tCExecution.getTestCaseObj().getUserAgent(), tCExecution.getUserAgent());410 if (!StringUtil.isNullOrEmpty(usedUserAgent)) {411 options.addArguments("--user-agent=" + usedUserAgent);412 }413 capabilities.setCapability(ChromeOptions.CAPABILITY, options);414 } else if (browser.contains("android")) {415 capabilities = DesiredCapabilities.android();416 } else if (browser.contains("ipad")) {417 capabilities = DesiredCapabilities.ipad();418 } else if (browser.contains("iphone")) {419 capabilities = DesiredCapabilities.iphone();420 } else if (browser.contains("opera")) {421 capabilities = DesiredCapabilities.opera();422 } else if (browser.contains("safari")) {423 capabilities = DesiredCapabilities.safari();424 } else {425 LOG.warn("Not supported Browser : " + browser);426 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);427 mes.setDescription(mes.getDescription().replace("%MES%", "Browser '" + browser + "' is not supported"));428 mes.setDescription("Not supported Browser : " + browser);429 throw new CerberusException(mes);430 }431 } catch (CerberusException ex) {432 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);433 mes.setDescription(mes.getDescription().replace("%MES%", "Failed to set capability on the browser '" + browser + "' due to " + ex.getMessageError().getDescription()));434 throw new CerberusException(mes);435 }436 return capabilities;437 }438 /**439 * This method determine which user agent to use.440 *441 * @param userAgentTestCase442 * @param userAgentRobot443 * @return String containing the userAgent to use444 */445 private String getUserAgentToUse(String userAgentTestCase, String userAgentRobot) {446 if (StringUtil.isNullOrEmpty(userAgentRobot) && StringUtil.isNullOrEmpty(userAgentTestCase)) {447 return "";448 } else {449 return StringUtil.isNullOrEmpty(userAgentTestCase) ? userAgentRobot : userAgentTestCase;450 }451 }452 /**453 * This method determine which screenSize to use.454 *455 * @param screenSizeTestCase456 * @param screenSizeRobot457 * @return String containing the userAgent to use458 */459 private String getScreenSizeToUse(String screenSizeTestCase, String screenSizeRobot) {460 if (StringUtil.isNullOrEmpty(screenSizeRobot) && StringUtil.isNullOrEmpty(screenSizeTestCase)) {461 return "";462 } else {463 return StringUtil.isNullOrEmpty(screenSizeTestCase) ? screenSizeRobot : screenSizeTestCase;464 }465 }466 @Override467 public boolean stopServer(Session session) {468 if (session.isStarted()) {469 try {470 // Wait 2 sec till HAR is exported471 Thread.sleep(2000);472 } catch (InterruptedException ex) {473 LOG.error(ex.toString());474 }475 LOG.info("Stop execution session");476 session.quit();477 return true;478 }479 return false;480 }481 private static void getIPOfNode(TestCaseExecution tCExecution) {482 try {483 Session session = tCExecution.getSession();484 HttpCommandExecutor ce = (HttpCommandExecutor) ((RemoteWebDriver) session.getDriver()).getCommandExecutor();485 SessionId sessionId = ((RemoteWebDriver) session.getDriver()).getSessionId();486 String hostName = ce.getAddressOfRemoteServer().getHost();487 int port = ce.getAddressOfRemoteServer().getPort();488 HttpHost host = new HttpHost(hostName, port);489 HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();490 URL sessionURL = new URL(SeleniumServerService.getBaseUrl(session.getHost(), session.getPort()) + "/grid/api/testsession?session=" + sessionId);491 BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());492 HttpResponse response = client.execute(host, r);493 if (!response.getStatusLine().toString().contains("403")494 && !response.getEntity().getContentType().getValue().contains("text/html")) {495 InputStream contents = response.getEntity().getContent();496 StringWriter writer = new StringWriter();497 IOUtils.copy(contents, writer, "UTF8");498 JSONObject object = new JSONObject(writer.toString());499 URL myURL = new URL(object.getString("proxyId"));500 if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {501 tCExecution.setIp(myURL.getHost());502 tCExecution.setPort(String.valueOf(myURL.getPort()));503 }504 }505 } catch (IOException ex) {506 LOG.error(ex.toString());507 } catch (JSONException ex) {508 LOG.error(ex.toString());509 }510 }511 @Override512 public Capabilities getUsedCapabilities(Session session) {513 Capabilities caps = ((RemoteWebDriver) session.getDriver()).getCapabilities();514 return caps;515 }516 private void setScreenSize(WebDriver driver, Integer width, Integer length) {...

Full Screen

Full Screen

Source:Session.java Github

copy

Full Screen

...101 }102 public void setHost(String host) {103 this.host = host;104 }105 public String getPort() {106 return port;107 }108 public void setPort(String port) {109 this.port = port;110 }111 public WebDriver getDriver() {112 return driver;113 }114 public void setDriver(WebDriver driver) {115 this.driver = driver;116 }117 public boolean isStarted() {118 return started;119 }...

Full Screen

Full Screen

getPort

Using AI Code Generation

copy

Full Screen

1package cerberus;2import org.cerberus.engine.entity.Selenium;3public class 3 {4 public static void main(String[] args) {5 Selenium s = new Selenium();6 System.out.println(s.getPort());7 }8}9package cerberus;10import org.cerberus.engine.entity.Selenium;11public class 4 {12 public static void main(String[] args) {13 Selenium s = new Selenium();14 System.out.println(s.getHost());15 }16}17package cerberus;18import org.cerberus.engine.entity.Selenium;19public class 5 {20 public static void main(String[] args) {21 Selenium s = new Selenium();22 System.out.println(s.getBrowser());23 }24}25package cerberus;26import org.cerberus.engine.entity.Selenium;27public class 6 {28 public static void main(String[] args) {29 Selenium s = new Selenium();30 System.out.println(s.getPlatform());31 }32}33package cerberus;34import org.cerberus.engine.entity.Selenium;35public class 7 {36 public static void main(String[] args) {37 Selenium s = new Selenium();38 System.out.println(s.getApplication());39 }40}41package cerberus;42import org.cerberus.engine.entity.Selenium;43public class 8 {44 public static void main(String[] args) {45 Selenium s = new Selenium();46 System.out.println(s.getCapabilities());47 }48}49package cerberus;50import org.cerberus.engine.entity.Selenium;51public class 9 {52 public static void main(String[] args) {53 Selenium s = new Selenium();54 System.out.println(s.getCapabilitiesAsJSONObject());55 }56}

Full Screen

Full Screen

getPort

Using AI Code Generation

copy

Full Screen

1package org.cerberus.engine.entity;2import org.cerberus.engine.entity.Selenium;3public class TestGetPort {4 public static void main(String[] args) {5 Selenium s = new Selenium();6 String port = s.getPort();7 System.out.println("Port is " + port);8 }9}10package org.cerberus.engine.entity;11import org.cerberus.engine.entity.Selenium;12public class TestGetPort {13 public static void main(String[] args) {14 Selenium s = new Selenium();15 String port = s.getPort();16 System.out.println("Port is " + port);17 }18}19package org.cerberus.engine.entity;20import org.cerberus.engine.entity.Selenium;21public class TestGetPort {22 public static void main(String[] args) {23 Selenium s = new Selenium();24 String port = s.getPort();25 System.out.println("Port is " + port);26 }27}28package org.cerberus.engine.entity;29import org.cerberus.engine.entity.Selenium;30public class TestGetPort {31 public static void main(String[] args) {32 Selenium s = new Selenium();33 String port = s.getPort();34 System.out.println("Port is " + port);35 }36}37package org.cerberus.engine.entity;38import org.cerberus.engine.entity.Selenium;39public class TestGetPort {40 public static void main(String[] args) {41 Selenium s = new Selenium();42 String port = s.getPort();43 System.out.println("Port is " + port);44 }45}46package org.cerberus.engine.entity;47import org.cerberus.engine.entity.Selenium;48public class TestGetPort {49 public static void main(String[] args) {50 Selenium s = new Selenium();51 String port = s.getPort();52 System.out.println("Port is " +

Full Screen

Full Screen

getPort

Using AI Code Generation

copy

Full Screen

1import org.cerberus.engine.entity.Selenium;2public class 3 {3 public static void main(String[] args) {4 Selenium sel = new Selenium();5 System.out.println("Port number of the running selenium server is " + sel.getPort());6 }7}

Full Screen

Full Screen

getPort

Using AI Code Generation

copy

Full Screen

1package org.cerberus.engine.entity;2import org.openqa.selenium.server.SeleniumServer;3import org.openqa.selenium.server.RemoteControlConfiguration;4public class Selenium {5 public static void main(String[] args) throws Exception {6 RemoteControlConfiguration rcc = new RemoteControlConfiguration();7 rcc.setPort(4444);8 SeleniumServer server = new SeleniumServer(rcc);9 server.start();10 System.out.println("The port number is: " + server.getPort());11 server.stop();12 }13}14package org.cerberus.engine.entity;15import org.openqa.selenium.server.SeleniumServer;16import org.openqa.selenium.server.RemoteControlConfiguration;17public class Selenium {18 public static void main(String[] args) throws Exception {19 RemoteControlConfiguration rcc = new RemoteControlConfiguration();20 rcc.setPort(4444);21 SeleniumServer server = new SeleniumServer(rcc);22 server.start();23 System.out.println("The port number is: " + server.getPort());24 server.stop();25 }26}27package org.cerberus.engine.entity;28import org.openqa.selenium.server.SeleniumServer;29import org.openqa.selenium.server.RemoteControlConfiguration;30public class Selenium {31 public static void main(String[] args) throws Exception {32 RemoteControlConfiguration rcc = new RemoteControlConfiguration();33 rcc.setPort(4444);34 SeleniumServer server = new SeleniumServer(rcc);35 server.start();36 System.out.println("The port number is: " + server.getPort());37 server.stop();38 }39}40package org.cerberus.engine.entity;41import org.openqa.selenium.server.SeleniumServer;42import org.openqa.selenium.server.RemoteControlConfiguration;43public class Selenium {44 public static void main(String[] args) throws Exception {45 RemoteControlConfiguration rcc = new RemoteControlConfiguration();46 rcc.setPort(4444);

Full Screen

Full Screen

getPort

Using AI Code Generation

copy

Full Screen

1package cerberus;2import org.cerberus.engine.entity.Selenium;3public class 3 {4 public static void main(String[] args) {5 Selenium selenium = new Selenium();6 System.out.println("Port: " + selenium.getPort());7 System.out.println("Browser: " + selenium.getBrowser());8 System.out.println("Browser Version: " + selenium.getBrowserVersion());9 }10}11package cerberus;12import org.cerberus.engine.entity.Selenium;13public class 4 {14 public static void main(String[] args) {15 Selenium selenium = new Selenium();16 System.out.println("Browser: " + selenium.getBrowser());17 System.out.println("Browser Version: " + selenium.getBrowserVersion());18 System.out.println("Port: " + selenium.getPort());19 }20}21package cerberus;22import org.cerberus.engine.entity.Selenium;23public class 5 {24 public static void main(String[] args) {25 Selenium selenium = new Selenium();26 System.out.println("Browser Version: " + selenium.getBrowserVersion());27 System.out.println("Port

Full Screen

Full Screen

getPort

Using AI Code Generation

copy

Full Screen

1package org.cerberus.test;2import org.cerberus.engine.entity.Selenium;3public class TestGetPort {4 public static void main(String[] args) {5 Selenium s = new Selenium();6 int port = s.getPort();7 System.out.println("Port Number: " + port);8 }9}10package org.cerberus.test;11import org.cerberus.engine.entity.Selenium;12public class TestGetPort {13 public static void main(String[] args) {14 Selenium s = new Selenium();15 int port = s.getPort();

Full Screen

Full Screen

getPort

Using AI Code Generation

copy

Full Screen

1import com.thoughtworks.selenium.*;2import org.cerberus.engine.entity.Selenium;3import java.io.IOException;4public class 3 {5 public static void main(String[] args) throws IOException {6 int port = Selenium.getPort();7 selenium.start();8 selenium.open("/");9 selenium.verifyTitle("Google");10 selenium.stop();11 }12}13import com.thoughtworks.selenium

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Cerberus-source automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful