How to use getHost method of org.cerberus.engine.entity.Session class

Best Cerberus-source code snippet using org.cerberus.engine.entity.Session.getHost

Source:RobotServerService.java Github

copy

Full Screen

...189 session.setCerberus_selenium_autoscroll(cerberus_selenium_autoscroll);190 session.setCerberus_selenium_autoscroll_vertical_offset(cerberus_selenium_autoscroll_vertical_offset);191 session.setCerberus_selenium_autoscroll_horizontal_offset(cerberus_selenium_autoscroll_horizontal_offset);192 tCExecution.setSession(session);193 tCExecution.setRobotProvider(guessRobotProvider(session.getHost()));194 LOG.debug("Session is set.");195 /**196 * Starting Cerberus Executor Proxy if it has been activated at197 * robot level.198 */199 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {200 LOG.debug("Start Remote Proxy");201 executorService.startRemoteProxy(tCExecution);202 LOG.debug("Started Remote Proxy on port:" + tCExecution.getRemoteProxyPort());203 }204 /**205 * SetUp Capabilities206 */207 LOG.debug("Set Capabilities");208 MutableCapabilities caps = this.setCapabilities(tCExecution);209 session.setDesiredCapabilities(caps);210 LOG.debug("Set Capabilities - retreived");211 /**212 * We record Caps list at the execution level.213 */214 try {215 // Init additionalFinalCapabilities and set it from real caps.216 List<RobotCapability> additionalFinalCapabilities = new ArrayList<>();217 for (Map.Entry cap : caps.asMap().entrySet()) {218 additionalFinalCapabilities.add(factoryRobotCapability.create(0, "", cap.getKey().toString(), cap.getValue().toString()));219 }220 // Init inputCapabilities and set it from Robot values.221 List<RobotCapability> inputCapabilities = new ArrayList<>();222 if (tCExecution.getRobotObj() != null) {223 inputCapabilities = tCExecution.getRobotObj().getCapabilities();224 }225 tCExecution.addFileList(recorderService.recordCapabilities(tCExecution, inputCapabilities, additionalFinalCapabilities));226 } catch (Exception ex) {227 LOG.error("Exception Saving Robot Caps " + tCExecution.getId() + " Exception :" + ex.toString(), ex);228 }229 /**230 * SetUp Proxy231 */232 String hubUrl = StringUtil.cleanHostURL(RobotServerService.getBaseUrl(StringUtil.formatURLCredential(233 tCExecution.getSession().getHostUser(),234 tCExecution.getSession().getHostPassword(), session.getHost()),235 session.getPort())) + "/wd/hub";236 LOG.debug("Hub URL :" + hubUrl);237 URL url = new URL(hubUrl);238 HttpCommandExecutor executor = null;239 boolean isProxy = proxyService.useProxy(hubUrl, system);240// HttpClientBuilder builder = HttpClientBuilder.create();241 Factory factory = new OkHttpClient.Factory();242 // Timeout Management243 int robotTimeout = parameterService.getParameterIntegerByKey("cerberus_robot_timeout", system, 60000);244 Duration rbtTimeOut = Duration.ofMillis(robotTimeout);245 factory.builder().connectionTimeout(rbtTimeOut);246// RequestConfig.Builder requestBuilder = RequestConfig.custom();247// requestBuilder = requestBuilder.setConnectTimeout(robotTimeout);248// requestBuilder = requestBuilder.setConnectionRequestTimeout(robotTimeout);249// requestBuilder = requestBuilder.setSocketTimeout(robotTimeout);250// builder.setDefaultRequestConfig(requestBuilder.build());251 if (isProxy) {252 // Proxy Management253 String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", system, DEFAULT_PROXY_HOST);254 int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", system, DEFAULT_PROXY_PORT);255// HttpHost proxy = new HttpHost(proxyHost, proxyPort);256// SocketAddress sa = new SocketAddress() {257// }258 java.net.Proxy myproxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));259// Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);260// builder.setProxy(proxy);261 if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system, DEFAULT_PROXYAUTHENT_ACTIVATE)) {262 String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", system, DEFAULT_PROXYAUTHENT_USER);263 String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", system, DEFAULT_PROXYAUTHENT_PASSWORD);264 Authenticator proxyAuthenticator = new Authenticator() {265 public Request authenticate(Route route, Response response) throws IOException {266 String credential = Credentials.basic(proxyUser, proxyPassword);267 return response.request().newBuilder()268 .header("Proxy-Authorization", credential)269 .build();270 }271 };272 factory.builder().proxy(myproxy);273// CredentialsProvider credsProvider = new BasicCredentialsProvider();274//275// credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));276//277// if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {278// credsProvider.setCredentials(279// new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())),280// new UsernamePasswordCredentials(tCExecution.getSession().getHostUser(), tCExecution.getSession().getHostPassword())281// );282// }283// builder.setDefaultCredentialsProvider(credsProvider);284 } else {285 factory.builder().proxy(myproxy);286 }287 } else {288 factory.builder().proxy(java.net.Proxy.NO_PROXY);289 }290 executor = new HttpCommandExecutor(new HashMap<>(), url, factory);291// executor = new HttpCommandExecutor(new HashMap<>(), url);292 /**293 * SetUp Driver294 */295 LOG.debug("Set Driver");296 WebDriver driver = null;297 AppiumDriver appiumDriver = null;298 switch (tCExecution.getApplicationObj().getType().toUpperCase()) {299 case Application.TYPE_GUI:300 if (caps.getPlatform() != null && caps.getPlatform().is(Platform.ANDROID)) {301 // Appium does not support connection from HTTPCommandExecutor. When connecting from Executor, it stops to work after a couple of instructions.302 appiumDriver = new AndroidDriver(url, caps);303 driver = (WebDriver) appiumDriver;304 } else if (caps.getPlatform() != null && (caps.getPlatform().is(Platform.IOS) || caps.getPlatform().is(Platform.MAC))) {305 appiumDriver = new IOSDriver(url, caps);306 driver = (WebDriver) appiumDriver;307 } else {308 driver = new RemoteWebDriver(executor, caps);309 }310 tCExecution.setRobotSessionID(getSession(driver, tCExecution.getRobotProvider()));311 break;312 case Application.TYPE_APK:313 // add a lock on app path this part of code, because we can't install 2 apk with the same name simultaneously314 String appUrl = null;315 if (caps.getCapability("app") != null) {316 appUrl = caps.getCapability("app").toString();317 }318 int toto = totocpt++;319 if (appUrl != null) { // FIX : appium can't install 2 apk simultaneously, so implement a litle latency between execution320 synchronized (this) {321 // 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)322 // provoque a latency if first test is already running and apk don't finish to be prepared323 if (apkAlreadyPrepare.containsKey(appUrl) && !apkAlreadyPrepare.get(appUrl)) {324 Thread.sleep(10000);325 } else {326 apkAlreadyPrepare.put(appUrl, false);327 }328 }329 }330 appiumDriver = new AndroidDriver(url, caps);331 if (apkAlreadyPrepare.containsKey(appUrl)) {332 apkAlreadyPrepare.put(appUrl, true);333 }334 driver = (WebDriver) appiumDriver;335 tCExecution.setRobotSessionID(getSession(driver, tCExecution.getRobotProvider()));336 break;337 case Application.TYPE_IPA:338 appiumDriver = new IOSDriver(url, caps);339 driver = (WebDriver) appiumDriver;340 tCExecution.setRobotSessionID(getSession(driver, tCExecution.getRobotProvider()));341 break;342 case Application.TYPE_FAT:343 /**344 * Check sikuli extension is reachable345 */346 if (!sikuliService.isSikuliServerReachable(session)) {347 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SIKULI_COULDNOTCONNECT);348 mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));349 mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));350 throw new CerberusException(mes);351 }352 /**353 * If CountryEnvParameter IP is set, open the App354 */355 if (!tCExecution.getCountryEnvironmentParameters().getIp().isEmpty()) {356 sikuliService.doSikuliActionOpenApp(session, tCExecution.getCountryEnvironmentParameters().getIp());357 }358 break;359 }360 /**361 * We record Server Side Caps.362 */363 if (driver != null) {364 try {365 // Init additionalFinalCapabilities and set it from real caps.366 List<RobotCapability> serverCapabilities = new ArrayList<>();367 for (Map.Entry cap : ((RemoteWebDriver) driver).getCapabilities().asMap().entrySet()) {368 serverCapabilities.add(factoryRobotCapability.create(0, "", cap.getKey().toString(), cap.getValue().toString()));369 }370 tCExecution.addFileList(recorderService.recordServerCapabilities(tCExecution, serverCapabilities));371 } catch (Exception ex) {372 LOG.error("Exception Saving Server Robot Caps " + tCExecution.getId(), ex);373 }374 }375 /**376 * Defining the timeout at the driver level. Only in case of not377 * Appium Driver (see378 * https://github.com/vertigo17/Cerberus/issues/754)379 */380 if (driver != null && appiumDriver == null) {381 driver.manage().timeouts().pageLoadTimeout(cerberus_selenium_pageLoadTimeout, TimeUnit.MILLISECONDS);382 driver.manage().timeouts().implicitlyWait(cerberus_selenium_implicitlyWait, TimeUnit.MILLISECONDS);383 driver.manage().timeouts().setScriptTimeout(cerberus_selenium_setScriptTimeout, TimeUnit.MILLISECONDS);384 }385 if (appiumDriver != null) {386 appiumDriver.manage().timeouts().implicitlyWait(cerberus_appium_wait_element, TimeUnit.MILLISECONDS);387 }388 tCExecution.getSession().setDriver(driver);389 tCExecution.getSession().setAppiumDriver(appiumDriver);390 /**391 * If Gui application, maximize window Get IP of Node in case of392 * remote Server. Maximize does not work for chrome browser We also393 * get the Real UserAgent from the browser.394 */395 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI)396 && !caps.getPlatform().equals(Platform.ANDROID) && !caps.getPlatform().equals(Platform.IOS)397 && !caps.getPlatform().equals(Platform.MAC)) {398 if (!caps.getBrowserName().equals(BrowserType.CHROME)) {399 driver.manage().window().maximize();400 }401 getIPOfNode(tCExecution);402 /**403 * If screenSize is defined, set the size of the screen.404 */405 String targetScreensize = getScreenSizeToUse(tCExecution.getTestCaseObj().getScreenSize(), tCExecution.getScreenSize());406 LOG.debug("Selenium resolution : " + targetScreensize);407 if (!tCExecution.getBrowser().equalsIgnoreCase(BrowserType.CHROME)) {408 // For chrome the resolution has already been defined at capabilities level.409 if ((!StringUtil.isNullOrEmpty(targetScreensize)) && targetScreensize.contains("*")) {410 Integer screenWidth = Integer.valueOf(targetScreensize.split("\\*")[0]);411 Integer screenLength = Integer.valueOf(targetScreensize.split("\\*")[1]);412 setScreenSize(driver, screenWidth, screenLength);413 LOG.debug("Selenium resolution Activated : " + screenWidth + "*" + screenLength);414 }415 }416 tCExecution.setScreenSize(getScreenSize(driver));417 tCExecution.setRobotDecli(tCExecution.getRobotDecli().replace("%SCREENSIZE%", tCExecution.getScreenSize()));418 String userAgent = (String) ((JavascriptExecutor) driver).executeScript("return navigator.userAgent;");419 tCExecution.setUserAgent(userAgent);420 }421 // unlock device if deviceLockUnlock is active422 if (tCExecution.getRobotExecutorObj() != null && appiumDriver != null && appiumDriver instanceof LocksDevice423 && "Y".equals(tCExecution.getRobotExecutorObj().getDeviceLockUnlock())) {424 ((LocksDevice) appiumDriver).unlockDevice();425 }426 tCExecution.getSession().setStarted(true);427 } catch (CerberusException exception) {428 LOG.error(exception.toString(), exception);429 throw new CerberusException(exception.getMessageError(), exception);430 } catch (MalformedURLException exception) {431 LOG.error(exception.toString(), exception);432 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_URL_MALFORMED);433 mes.setDescription(mes.getDescription().replace("%URL%", tCExecution.getSession().getHost() + ":" + tCExecution.getSession().getPort()));434 throw new CerberusException(mes, exception);435 } catch (UnreachableBrowserException exception) {436 LOG.warn("Could not connect to : " + tCExecution.getSeleniumIP() + ":" + tCExecution.getSeleniumPort());437// LOG.error("UnreachableBrowserException catched.", exception);438 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SELENIUM_COULDNOTCONNECT);439 mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));440 mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));441 mes.setDescription(mes.getDescription().replace("%ERROR%", exception.toString()));442 throw new CerberusException(mes, exception);443 } catch (Exception exception) {444 LOG.error(exception.toString(), exception);445 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);446 mes.setDescription(mes.getDescription().replace("%MES%", exception.toString()));447 executorService.stopRemoteProxy(tCExecution);448 throw new CerberusException(mes, exception);449 } finally {450 executionThreadPoolService.executeNextInQueueAsynchroneously(false);451 }452 }453 private String getSession(WebDriver driver, String robotProvider) {454 String session = "";455 switch (robotProvider) {456 case TestCaseExecution.ROBOTPROVIDER_BROWSERSTACK:457 session = ((RemoteWebDriver) driver).getSessionId().toString();458 break;459 case TestCaseExecution.ROBOTPROVIDER_KOBITON:460 session = ((RemoteWebDriver) driver).getCapabilities().getCapability("kobitonSessionId").toString();461 break;462 case TestCaseExecution.ROBOTPROVIDER_NONE:463 session = ((RemoteWebDriver) driver).getSessionId().toString();464 break;465 default:466 }467 return session;468 }469 private String guessRobotProvider(String host) {470 if (host.contains("browserstack")) {471 return TestCaseExecution.ROBOTPROVIDER_BROWSERSTACK;472 }473 if (host.contains("kobiton")) {474 return TestCaseExecution.ROBOTPROVIDER_KOBITON;475 }476 return TestCaseExecution.ROBOTPROVIDER_NONE;477 }478 /**479 * Set DesiredCapabilities480 *481 * @param tCExecution482 * @return483 * @throws CerberusException484 */485 private MutableCapabilities setCapabilities(TestCaseExecution tCExecution) throws CerberusException {486 /**487 * Instanciate DesiredCapabilities488 */489 MutableCapabilities caps = new MutableCapabilities();490 // In case browser is not defined at that level, we force it to firefox.491 if (StringUtil.isNullOrEmpty(tCExecution.getBrowser())) {492 tCExecution.setBrowser("firefox");493 }494 /**495 * Set Browser Capabilities496 */497 caps = this.setCapabilityBrowser(caps, tCExecution.getBrowser(), tCExecution);498 /**499 * Loop on RobotCapabilities to feed DesiredCapabilities Capability must500 * be String, Integer or Boolean501 */502 List<RobotCapability> additionalCapabilities = new ArrayList<>();503 if (tCExecution.getRobotObj() != null) {504 additionalCapabilities = tCExecution.getRobotObj().getCapabilitiesDecoded();505 }506 if (additionalCapabilities != null) {507 for (RobotCapability additionalCapability : additionalCapabilities) {508 LOG.debug("RobotCaps on Robot : " + additionalCapability.getRobot() + " caps : " + additionalCapability.getCapability() + " Value : " + additionalCapability.getValue());509 if ((caps.getCapability(additionalCapability.getCapability()) == null)510 || ((caps.getCapability(additionalCapability.getCapability()) != null) && (caps.getCapability(additionalCapability.getCapability()).toString().equals("")))) { // caps does not already exist so we can set it.511 if (StringUtil.isBoolean(additionalCapability.getValue())) {512 caps.setCapability(additionalCapability.getCapability(), StringUtil.parseBoolean(additionalCapability.getValue()));513 } else if (StringUtil.isInteger(additionalCapability.getValue())) {514 caps.setCapability(additionalCapability.getCapability(), Integer.valueOf(additionalCapability.getValue()));515 } else {516 caps.setCapability(additionalCapability.getCapability(), additionalCapability.getValue());517 }518 }519 }520 } else {521 additionalCapabilities = new ArrayList<>();522 }523 /**524 * Feed DesiredCapabilities with values get from Robot525 */526 if (!StringUtil.isNullOrEmpty(tCExecution.getPlatform())) {527 if ((caps.getCapability("platform") == null)528 || ((caps.getCapability("platform") != null) && (caps.getCapability("platform").toString().equals("ANY") || caps.getCapability("platform").toString().equals("")))) {529 caps.setCapability("platformName", tCExecution.getPlatform());530 }531 }532 if (!StringUtil.isNullOrEmpty(tCExecution.getVersion())) {533 if ((caps.getCapability("version") == null)534 || ((caps.getCapability("version") != null) && (caps.getCapability("version").toString().equals("")))) {535 caps.setCapability("version", tCExecution.getVersion());536 }537 }538 if (tCExecution.getRobotExecutorObj() != null) {539 // Setting deviceUdid and device name from executor.540 if (!StringUtil.isNullOrEmpty(tCExecution.getRobotExecutorObj().getDeviceUuid())) {541 if ((caps.getCapability("udid") == null)542 || ((caps.getCapability("udid") != null) && (caps.getCapability("udid").toString().equals("")))) {543 caps.setCapability("udid", tCExecution.getRobotExecutorObj().getDeviceUuid());544 }545 }546 if (!StringUtil.isNullOrEmpty(tCExecution.getRobotExecutorObj().getDeviceName())) {547 if ((caps.getCapability("deviceName") == null)548 || ((caps.getCapability("deviceName") != null) && (caps.getCapability("deviceName").toString().equals("")))) {549 caps.setCapability("deviceName", tCExecution.getRobotExecutorObj().getDeviceName());550 }551 }552 if (!StringUtil.isNullOrEmpty(tCExecution.getRobotExecutorObj().getDeviceName())) {553 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)) {554 if ((caps.getCapability("systemPort") == null)555 || ((caps.getCapability("systemPort") != null) && (caps.getCapability("systemPort").toString().equals("")))) {556 caps.setCapability("systemPort", tCExecution.getRobotExecutorObj().getDevicePort());557 }558 } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_IPA)) {559 if ((caps.getCapability("wdaLocalPort") == null)560 || ((caps.getCapability("wdaLocalPort") != null) && (caps.getCapability("wdaLocalPort").toString().equals("")))) {561 caps.setCapability("wdaLocalPort", tCExecution.getRobotExecutorObj().getDevicePort());562 }563 }564 }565 }566 /**567 * if application is a mobile one, then set the "app" capability to the568 * application binary path569 */570 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)571 || tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_IPA)) {572 // Set the app capability with the application path573 if (!StringUtil.isNullOrEmpty(tCExecution.getMyHost())) {574 if (isNotAlreadyDefined(caps, "app")) {575 caps.setCapability("app", tCExecution.getMyHost());576 }577 } else {578 if (isNotAlreadyDefined(caps, "app")) {579 caps.setCapability("app", tCExecution.getCountryEnvironmentParameters().getIp());580 }581 }582 if (!StringUtil.isNullOrEmpty(tCExecution.getCountryEnvironmentParameters().getMobileActivity()) && tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)) {583 if (isNotAlreadyDefined(caps, "appWaitActivity")) {584 caps.setCapability("appWaitActivity", tCExecution.getCountryEnvironmentParameters().getMobileActivity());585 }586 }587 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)) {588 if (isNotAlreadyDefined(caps, "automationName")) {589 caps.setCapability("automationName", "UIAutomator2"); // use UIAutomator2 by default590 }591 }592 }593 /**594 * We record Selenium log at the end of the execution.595 */596 switch (tCExecution.getRobotProvider()) {597 case TestCaseExecution.ROBOTPROVIDER_BROWSERSTACK:598 if (!StringUtil.isNullOrEmpty(tCExecution.getTag()) && isNotAlreadyDefined(caps, "build")) {599 caps.setCapability("build", tCExecution.getTag());600 }601 if (isNotAlreadyDefined(caps, "project")) {602 caps.setCapability("project", tCExecution.getApplication());603 }604 if (isNotAlreadyDefined(caps, "name")) {605 String externalExeName = parameterService.getParameterStringByKey("cerberus_browserstack_defaultexename", tCExecution.getSystem(), "Exe : %EXEID%");606 externalExeName = externalExeName.replace("%EXEID%", String.valueOf(tCExecution.getId()));607 caps.setCapability("name", externalExeName);608 }609 if (tCExecution.getVerbose() >= 2) {610 if (isNotAlreadyDefined(caps, "browserstack.debug")) {611 caps.setCapability("browserstack.debug", true);612 }613 if (isNotAlreadyDefined(caps, "browserstack.console")) {614 caps.setCapability("browserstack.console", "warnings");615 }616 if (isNotAlreadyDefined(caps, "browserstack.networkLogs")) {617 caps.setCapability("browserstack.networkLogs", true);618 }619 }620 break;621 case TestCaseExecution.ROBOTPROVIDER_KOBITON:622 if (isNotAlreadyDefined(caps, "sessionName")) {623 String externalExeName = parameterService.getParameterStringByKey("cerberus_kobiton_defaultsessionname", tCExecution.getSystem(), "%EXEID% : %TEST% - %TESTCASE%");624 externalExeName = externalExeName.replace("%EXEID%", String.valueOf(tCExecution.getId()));625 externalExeName = externalExeName.replace("%APPLI%", String.valueOf(tCExecution.getApplication()));626 externalExeName = externalExeName.replace("%TAG%", String.valueOf(tCExecution.getTag()));627 externalExeName = externalExeName.replace("%TEST%", String.valueOf(tCExecution.getTest()));628 externalExeName = externalExeName.replace("%TESTCASE%", String.valueOf(tCExecution.getTestCase()));629 externalExeName = externalExeName.replace("%TESTCASEDESC%", String.valueOf(tCExecution.getTestCaseObj().getDescription()));630 caps.setCapability("sessionName", externalExeName);631 }632 if (isNotAlreadyDefined(caps, "sessionDescription")) {633 String externalExeName = parameterService.getParameterStringByKey("cerberus_kobiton_defaultsessiondescription", tCExecution.getSystem(), "%TESTCASEDESC%");634 externalExeName = externalExeName.replace("%EXEID%", String.valueOf(tCExecution.getId()));635 externalExeName = externalExeName.replace("%APPLI%", String.valueOf(tCExecution.getApplication()));636 externalExeName = externalExeName.replace("%TAG%", String.valueOf(tCExecution.getTag()));637 externalExeName = externalExeName.replace("%TEST%", String.valueOf(tCExecution.getTest()));638 externalExeName = externalExeName.replace("%TESTCASE%", String.valueOf(tCExecution.getTestCase()));639 externalExeName = externalExeName.replace("%TESTCASEDESC%", String.valueOf(tCExecution.getTestCaseObj().getDescription()));640 caps.setCapability("sessionDescription", externalExeName);641 }642 if (isNotAlreadyDefined(caps, "deviceGroup")) {643 caps.setCapability("deviceGroup", "KOBITON"); // use UIAutomator2 by default644 }645 break;646 case TestCaseExecution.ROBOTPROVIDER_NONE:647 break;648 default:649 }650 return caps;651 }652 private boolean isNotAlreadyDefined(MutableCapabilities caps, String capability) {653 return ((caps.getCapability(capability) == null)654 || ((caps.getCapability(capability) != null) && (caps.getCapability(capability).toString().equals(""))));655 }656 /**657 * Instantiate DesiredCapabilities regarding the browser658 *659 * @param capabilities660 * @param browser661 * @param tCExecution662 * @return663 * @throws CerberusException664 */665 private MutableCapabilities setCapabilityBrowser(MutableCapabilities capabilities, String browser, TestCaseExecution tCExecution) throws CerberusException {666 try {667 // Get User Agent to use.668 String usedUserAgent;669 usedUserAgent = getUserAgentToUse(tCExecution.getTestCaseObj().getUserAgent(), tCExecution.getUserAgent());670 switch (browser) {671 case "firefox":672 FirefoxOptions optionsFF = new FirefoxOptions();673 FirefoxProfile profile = new FirefoxProfile();674 profile.setPreference("app.update.enabled", false);675 try {676 Invariant invariant = invariantService.convert(invariantService.readByKey("COUNTRY", tCExecution.getCountry()));677 if (invariant.getGp2() == null) {678 LOG.warn("Country selected (" + tCExecution.getCountry() + ") has no value of GP2 in Invariant table, default language set to English (en)");679 profile.setPreference("intl.accept_languages", "en");680 } else {681 profile.setPreference("intl.accept_languages", invariant.getGp2());682 }683 } catch (CerberusException ex) {684 LOG.warn("Country selected (" + tCExecution.getCountry() + ") not in Invariant table, default language set to English (en)");685 profile.setPreference("intl.accept_languages", "en");686 }687 // Set UserAgent if testCaseUserAgent or robotUserAgent is defined688 if (!StringUtil.isNullOrEmpty(usedUserAgent)) {689 profile.setPreference("general.useragent.override", usedUserAgent);690 }691 if (tCExecution.getVerbose() <= 0) {692 optionsFF.setHeadless(true);693 }694 // Add the WebDriver proxy capability.695 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {696 Proxy proxy = new Proxy();697 proxy.setHttpProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());698 proxy.setSslProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());699 proxy.setProxyType(Proxy.ProxyType.MANUAL);700 LOG.debug("Setting Firefox proxy to : " + proxy.toString());701 optionsFF.setProxy(proxy);702 }703 optionsFF.setProfile(profile);704 // Accept Insecure Certificates.705 optionsFF.setAcceptInsecureCerts(true);706 return optionsFF;707 case "chrome":708 ChromeOptions optionsCH = new ChromeOptions();709 // Maximize windows for chrome browser710 String targetScreensize = getScreenSizeToUse(tCExecution.getTestCaseObj().getScreenSize(), tCExecution.getScreenSize());711 if ((!StringUtil.isNullOrEmpty(targetScreensize)) && targetScreensize.contains("*")) {712 Integer screenWidth = Integer.valueOf(targetScreensize.split("\\*")[0]);713 Integer screenLength = Integer.valueOf(targetScreensize.split("\\*")[1]);714 String sizeOpts = "--window-size=" + screenWidth + "," + screenLength;715 optionsCH.addArguments(sizeOpts);716 LOG.debug("Selenium resolution (for Chrome) Activated : " + screenWidth + "*" + screenLength);717 }718 optionsCH.addArguments("start-maximized");719 if (tCExecution.getVerbose() <= 0) {720 optionsCH.addArguments("--headless");721 }722 // Set UserAgent if necessary723 if (!StringUtil.isNullOrEmpty(usedUserAgent)) {724 optionsCH.addArguments("--user-agent=" + usedUserAgent);725 }726 // Add the WebDriver proxy capability.727 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {728 Proxy proxy = new Proxy();729 proxy.setHttpProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());730 proxy.setSslProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());731 proxy.setNoProxy("");732 proxy.setProxyType(Proxy.ProxyType.MANUAL);733 LOG.debug("Setting Chrome proxy to : " + proxy.toString());734 optionsCH.setCapability("proxy", proxy);735 }736 // Accept Insecure Certificates.737 optionsCH.setAcceptInsecureCerts(true);738 return optionsCH;739 case "safari":740 SafariOptions optionsSA = new SafariOptions();741 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {742 Proxy proxy = new Proxy();743 proxy.setHttpProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());744 proxy.setSslProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());745 optionsSA.setProxy(proxy);746 }747 return optionsSA;748 case "IE":749 InternetExplorerOptions optionsIE = new InternetExplorerOptions();750 // Add the WebDriver proxy capability.751 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {752 Proxy proxy = new Proxy();753 proxy.setHttpProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());754 proxy.setSslProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());755 proxy.setProxyType(Proxy.ProxyType.MANUAL);756 LOG.debug("Setting IE proxy to : " + proxy.toString());757 optionsIE.setCapability("proxy", proxy);758 }759 return optionsIE;760 case "edge":761 EdgeOptions optionsED = new EdgeOptions();762 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {763 Proxy proxy = new Proxy();764 proxy.setHttpProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());765 proxy.setSslProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());766 optionsED.setProxy(proxy);767 }768 return optionsED;769 case "opera":770 OperaOptions optionsOP = new OperaOptions();771 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {772 Proxy proxy = new Proxy();773 proxy.setHttpProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());774 proxy.setSslProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());775 optionsOP.setProxy(proxy);776 }777 optionsOP.setCapability("browser", "opera");778 // Forcing a profile in order to force UserAgent. This has been commented because it fail when using BrowserStack that does not allow to create the correcponding profile folder.779// if (!StringUtil.isNullOrEmpty(usedUserAgent)) {780// optionsOP.setCapability("opera.profile", "{profileName: \"foo\",userAgent: \"" + usedUserAgent + "\"}");781// }782 return optionsOP;783 case "android":784 if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {785 Proxy proxy = new Proxy();786 proxy.setHttpProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());787 proxy.setSslProxy(tCExecution.getRobotExecutorObj().getExecutorProxyHost() + ":" + tCExecution.getRemoteProxyPort());788 }789 capabilities = DesiredCapabilities.android();790 break;791 case "ipad":792 capabilities = DesiredCapabilities.ipad();793 break;794 case "iphone":795 capabilities = DesiredCapabilities.iphone();796 break;797 // Unfortunatly Yandex is not yet supported on BrowserStack. Once it will be it should look like that:798// case "yandex":799// capabilities = new DesiredCapabilities();800// capabilities.setCapability("browser", "Yandex");801// capabilities.setCapability("browser_version", "14.12");802// break;803 default:804 LOG.warn("Not supported Browser : " + browser);805 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);806 mes.setDescription(mes.getDescription().replace("%MES%", "Browser '" + browser + "' is not supported"));807 mes.setDescription("Not supported Browser : " + browser);808 throw new CerberusException(mes);809 }810 } catch (CerberusException ex) {811 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);812 mes.setDescription(mes.getDescription().replace("%MES%", "Failed to set capability on the browser '" + browser + "' due to " + ex.getMessageError().getDescription()));813 throw new CerberusException(mes);814 }815 return capabilities;816 }817 /**818 * This method determine which user agent to use.819 *820 * @param userAgentTestCase821 * @param userAgentRobot822 * @return String containing the userAgent to use823 */824 private String getUserAgentToUse(String userAgentTestCase, String userAgentRobot) {825 if (StringUtil.isNullOrEmpty(userAgentRobot) && StringUtil.isNullOrEmpty(userAgentTestCase)) {826 return "";827 } else {828 return StringUtil.isNullOrEmpty(userAgentTestCase) ? userAgentRobot : userAgentTestCase;829 }830 }831 /**832 * This method determine which screenSize to use.833 *834 * @param screenSizeTestCase835 * @param screenSizeRobot836 * @return String containing the screensize to use837 */838 private String getScreenSizeToUse(String screenSizeTestCase, String screenSizeRobot) {839 if (StringUtil.isNullOrEmpty(screenSizeRobot) && StringUtil.isNullOrEmpty(screenSizeTestCase)) {840 return "";841 } else {842 return StringUtil.isNullOrEmpty(screenSizeTestCase) ? screenSizeRobot : screenSizeTestCase;843 }844 }845 @Override846 public boolean stopServer(TestCaseExecution tce) {847 Session session = tce.getSession();848 if (session.isStarted()) {849 try {850 // Wait 2 sec till HAR is exported851 Thread.sleep(2000);852 } catch (InterruptedException ex) {853 LOG.error(ex.toString(), ex);854 }855 /**856 * We remove manually the package if it is defined.857 */858 if (session.getAppiumDriver() != null && tce.getCountryEnvironmentParameters() != null859 && !StringUtil.isNullOrEmpty(tce.getCountryEnvironmentParameters().getMobilePackage())) {860 session.getAppiumDriver().removeApp(tce.getCountryEnvironmentParameters().getMobilePackage());861 }862 /**863 * We lock device if deviceLockUnlock is active.864 */865 // 866 if (tce.getRobotExecutorObj() != null && session.getAppiumDriver() != null && session.getAppiumDriver() instanceof LocksDevice867 && "Y".equals(tce.getRobotExecutorObj().getDeviceLockUnlock())) {868 ((LocksDevice) session.getAppiumDriver()).lockDevice();869 }870 /**871 * We record Selenium log at the end of the execution.872 */873 switch (tce.getRobotProvider()) {874 case TestCaseExecution.ROBOTPROVIDER_BROWSERSTACK:875 try {876 tce.addFileList(recorderService.recordSeleniumLog(tce));877 } catch (Exception ex) {878 LOG.error("Exception Getting Selenium Logs " + tce.getId(), ex);879 }880// try {881// tce.addFileList(recorderService.recordBrowserstackSeleniumLog(tce));882// } catch (Exception ex) {883// LOG.error("Exception Getting Browserstack Selenium Logs " + tce.getId(), ex);884// }885// break;886 case TestCaseExecution.ROBOTPROVIDER_NONE:887 try {888 tce.addFileList(recorderService.recordSeleniumLog(tce));889 } catch (Exception ex) {890 LOG.error("Exception Getting Selenium Logs " + tce.getId(), ex);891 }892 break;893 default:894 }895 /**896 * We record Har log at the end of the execution.897 */898 switch (tce.getRobotProvider()) {899 case TestCaseExecution.ROBOTPROVIDER_BROWSERSTACK:900// try {901// String url = "http://api.bs.com/getHar?uuid=" + tce.getRobotSessionID();902// tce.addFileList(recorderService.recordBrowserstackHarLog(tce, url));903// } catch (Exception ex) {904// LOG.error("Exception Getting Browserstack HAR File " + tce.getId(), ex);905// }906 break;907 case TestCaseExecution.ROBOTPROVIDER_NONE:908 break;909 default:910 }911 try {912 // Get Har File when Cerberus Executor is activated.913 // If proxy started and parameter verbose >= 1 activated914 if ("Y".equals(tce.getRobotExecutorObj().getExecutorProxyActive())915 && tce.getVerbose() >= 1) {916 if (parameterService.getParameterBooleanByKey("cerberus_networkstatsave_active", tce.getSystem(), false)) {917 // Before collecting the stats, we wait the network idles for few minutes918 executorService.waitForIdleNetwork(tce.getRobotExecutorObj().getExecutorExtensionHost(), tce.getRobotExecutorObj().getExecutorExtensionPort(), tce.getRemoteProxyUUID(), tce.getSystem());919 // We now get the har data.920 JSONObject har = executorService.getHar(null, false, tce.getRobotExecutorObj().getExecutorExtensionHost(), tce.getRobotExecutorObj().getExecutorExtensionPort(), tce.getRemoteProxyUUID(), tce.getSystem());921 // and enrich it with stat entry.922 har = harService.enrichWithStats(har, tce.getCountryEnvironmentParameters().getDomain(), tce.getSystem());923 /**924 * We convert the har to database record HttpStat and925 * save it to database.926 */927 try {928 AnswerItem<TestCaseExecutionHttpStat> answHttpStat = testCaseExecutionHttpStatService.convertFromHarWithStat(tce, har);929 tce.setHttpStat(answHttpStat.getItem());930 testCaseExecutionHttpStatService.create(answHttpStat.getItem());931 } catch (Exception ex) {932 LOG.warn("Exception collecting and saving stats for execution " + tce.getId() + " Exception : " + ex.toString());933 }934 }935 }936 } catch (Exception ex) {937 LOG.error("Exception Getting Har File from Cerberus Executor " + tce.getId(), ex);938 }939 /**940 * We Stop the Robot Session (Selenium or Appium).941 */942 LOG.info("Stop execution robot session");943 if (tce.getRobotProvider().equals(TestCaseExecution.ROBOTPROVIDER_KOBITON)) {944 // For Kobiton, we should first close Appium session.945 if (session.getAppiumDriver() != null) {946 session.getAppiumDriver().close();947 }948 if (session.getDriver() != null) {949 session.getDriver().quit();950 }951 } else {952 session.quit();953 }954 return true;955 }956 return false;957 }958 private static void getIPOfNode(TestCaseExecution tCExecution) {959 try {960 Session session = tCExecution.getSession();961 HttpCommandExecutor ce = (HttpCommandExecutor) ((RemoteWebDriver) session.getDriver()).getCommandExecutor();962 SessionId sessionId = ((RemoteWebDriver) session.getDriver()).getSessionId();963 String hostName = ce.getAddressOfRemoteServer().getHost();964 int port = ce.getAddressOfRemoteServer().getPort();965 HttpHost host = new HttpHost(hostName, port);966 HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();967 URL sessionURL = new URL(RobotServerService.getBaseUrl(session.getHost(), session.getPort()) + "/grid/api/testsession?session=" + sessionId);968 BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());969 HttpResponse response = client.execute(host, r);970 if (!response.getStatusLine().toString().contains("403")971 && !response.getEntity().getContentType().getValue().contains("text/html")) {972 InputStream contents = response.getEntity().getContent();973 StringWriter writer = new StringWriter();974 IOUtils.copy(contents, writer, "UTF8");975 JSONObject object = new JSONObject(writer.toString());976 if (object.has("proxyId")) {977 URL myURL = new URL(object.getString("proxyId"));978 if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {979 tCExecution.setRobotHost(myURL.getHost());980 tCExecution.setRobotPort(String.valueOf(myURL.getPort()));981 }982 } else {983 LOG.debug("'proxyId' json data not available from remote Selenium Server request : " + writer.toString());984 }985 }986 } catch (IOException | JSONException ex) {987 LOG.error(ex.toString(), ex);988 }989 }990 @Override991 public Capabilities getUsedCapabilities(Session session) {992 Capabilities caps = ((RemoteWebDriver) session.getDriver()).getCapabilities();993 return caps;...

Full Screen

Full Screen

Source:SeleniumServerService.java Github

copy

Full Screen

...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 }...

Full Screen

Full Screen

getHost

Using AI Code Generation

copy

Full Screen

1import org.cerberus.engine.entity.Session;2import org.cerberus.engine.entity.IApplication;3import org.cerberus.engine.entity.IUser;4import org.cerberus.engine.entity.IEnvironment;5import org.cerberus.engine.entity.IBuildRevisionInvariant;6import org.cerberus.engine.entity.IBuildRevisionBatch;7import org.cerberus.engine.entity.IBuildRevisionBatchContent;8import org.cerberus.engine.entity.ISystem;9import org.cerberus.engine.entity.IInvariant;10import org.cerberus.engine.entity.ITestCase;11import org.cerberus.engine.entity.IParameter;12import org.cerberus.engine.entity.IProperty;13import org.cerberus.engine.entity.IInvariantCountry;14import org.cerberus.engine.entity.IInvariantCountryProperty;15import org.cerberus.engine.entity.IInvariantEnvironment;16import org.cerberus.engine.entity.IInvariantEnvironmentProperty;17import org.cerberus.engine.entity.IInvariantProperty;18import org.cerberus.engine.entity.IInvariantTestCase;19import org.cerberus.engine.entity.IInvariantTestCaseProperty;20import org.cerberus.engine.entity.IInvariantUser;21import org.cerberus.engine.entity.IInvariantUserProperty;22import org.cerberus.engine.entity.ITestCaseCountry;23import org.cerberus.engine.entity.ITestCaseCountryProperties;24import org.cerberus.engine.entity.ITestCaseStep;25import org.cerberus.engine.entity.ITestCaseStepAction;26import org.cerberus.engine.entity.IRobot;27import org.cerberus.engine.entity.IRobotCapability;28import org.cerberus.engine.entity.IRobotExecutor;29import org.cerberus.engine.entity.IRobotHost;30import org.cerberus.engine.entity.IRobotImage;31import org.cerberus.engine.entity.IRobotImageCapability;32import org.cerberus.engine.entity.IRobotImageExecutor;33import org.cerberus.engine.entity.IRobotImageHost;34import org.cerberus.engine.entity.IRobotImageProperty;35import org.cerberus.engine.entity.IRobotProperty;36import org.cerberus.engine.entity.IRobotProvider;37import org.cerberus.engine.entity.IRobotProviderProperty;38import org.cerberus.engine.entity.IRobotSession;39import org.cerberus.engine.entity.IRobotSessionStepAction;40import org.cerberus.engine.entity.IRobotSessionStepActionControl;41import org.cer

Full Screen

Full Screen

getHost

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

getHost

Using AI Code Generation

copy

Full Screen

1String host = session.getHost();2System.out.println("host: " + host);3String port = session.getPort();4System.out.println("port: " + port);5String host = session.getHost();6System.out.println("host: " + host);7String port = session.getPort();8System.out.println("port: " + port);9String host = session.getHost();10System.out.println("host: " + host);11String port = session.getPort();12System.out.println("port: " + port);13String host = session.getHost();14System.out.println("host: " + host);15String port = session.getPort();16System.out.println("port: " + port);17String host = session.getHost();18System.out.println("host: " + host);19String port = session.getPort();20System.out.println("port: " + port);21String host = session.getHost();22System.out.println("host: " + host);23String port = session.getPort();24System.out.println("port: " + port);25String host = session.getHost();

Full Screen

Full Screen

getHost

Using AI Code Generation

copy

Full Screen

1import org.cerberus.engine.entity.Session;2import org.cerberus.engine.entity.SessionFactory;3public class 3 {4 public static void main(String args[]) {5 System.out.println(session.getHost());6 }7}8import org.cerberus.engine.entity.Session;9import org.cerberus.engine.entity.SessionFactory;10public class 4 {11 public static void main(String args[]) {12 System.out.println(session.getPort());13 }14}15import org.cerberus.engine.entity.Session;16import org.cerberus.engine.entity.SessionFactory;17public class 5 {18 public static void main(String args[]) {19 System.out.println(session.getProtocol());20 }21}22import org.cerberus.engine.entity.Session;23import org.cerberus.engine.entity.SessionFactory;24public class 6 {25 public static void main(String args[]) {26 System.out.println(session.getQuery());27 }28}29import org.cerberus.engine.entity.Session;30import org.cerberus.engine.entity.SessionFactory;31public class 7 {32 public static void main(String args[]) {33 System.out.println(session.getRef());34 }35}36import org.cerberus.engine.entity.Session;37import org.cerberus.engine.entity.SessionFactory;38public class 8 {39 public static void main(String args[]) {40 System.out.println(session.getURL());41 }42}

Full Screen

Full Screen

getHost

Using AI Code Generation

copy

Full Screen

1import org.cerberus.engine.entity.Session;2import org.cerberus.util.Base64;3import java.util.HashMap;4public class 3 {5 public static void main(String args[]) throws Exception {6 Session session = new Session();7 session.setHost("localhost");8 session.setPort(8080);9 session.setAppContext("Cerberus");10 session.setLogin("admin");11 session.setPassword("admin");12 session.setUseSSL(false);13 session.connect();14 HashMap hm = session.getHost();15 System.out.println("host = " + hm.get("host"));16 System.out.println("port = " + hm.get("port"));17 System.out.println("appContext = " + hm.get("appContext"));18 System.out.println("login = " + hm.get("login"));19 System.out.println("password = " + hm.get("password"));20 System.out.println("useSSL = " + hm.get("useSSL"));21 }22}23import org.cerberus.engine.entity.Session;24import org.cerberus.util.Base64;25import java.util.HashMap;26public class 4 {27 public static void main(String args[]) throws Exception {28 Session session = new Session();29 session.setHost("localhost");30 session.setPort(8080);31 session.setAppContext("Cerberus");32 session.setLogin("admin");33 session.setPassword("admin");34 session.setUseSSL(false);35 session.connect();36 HashMap hm = session.getHost();37 System.out.println("host = " + hm.get("host"));38 System.out.println("port = " + hm.get("port"));39 System.out.println("appContext = " + hm.get("appContext"));40 System.out.println("login = " + hm.get("login"));41 System.out.println("password = " + hm.get("password"));42 System.out.println("

Full Screen

Full Screen

getHost

Using AI Code Generation

copy

Full Screen

1import org.cerberus.engine.entity.*;2import org.cerberus.engine.*;3import org.cerberus.util.*;4public class 3 {5public static void main(String[] args) {6Session session = new Session();7System.out.println("Host: "+session.getHost());8System.out.println("Port: "+session.getPort());9System.out.println("URI: "+session.getURI());10System.out.println("Method: "+session.getMethod());11}12}13import org.cerberus.engine.entity.*;14import org.cerberus.engine.*;15import org.cerberus.util.*;16public class 4 {17public static void main(String[] args) {18Session session = new Session();19session.setHost("www.google.com");20session.setPort(80);21session.setURI("/search");22session.setMethod("GET");23System.out.println("Host: "+session.getHost());24System.out.println("Port: "+session.getPort());25System.out.println("URI: "+session.getURI());26System.out.println("Method: "+session.getMethod());27}28}29import org.cerberus.engine.entity.*;30import org.cerberus.engine.*;31import org.cerberus.util.*;32public class 5 {33public static void main(String[] args) {34Session session = new Session();35session.setParameter("q","hello");36System.out.println("Value of q parameter:

Full Screen

Full Screen

getHost

Using AI Code Generation

copy

Full Screen

1import org.cerberus.engine.entity.Session;2public class 3 {3 public static void main(String[] args) {4 Session session = new Session();5 String host = session.getHost();6 System.out.println(host);7 }8}9import org.cerberus.engine.entity.Session;10public class 4 {11 public static void main(String[] args) {12 Session session = new Session();13 String url = session.getCurrentUrl();14 System.out.println(url);15 }16}17import org.cerberus.engine.entity.Session;18public class 5 {19 public static void main(String[] args) {20 Session session = new Session();21 String title = session.getTitle();22 System.out.println(title);23 }24}

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.

Most used method in Session

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful