Best Cerberus-source code snippet using org.cerberus.engine.execution.impl.RobotServerService.getBaseUrl
Source:RobotServerService.java
...215 }216 /**217 * SetUp Proxy218 */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 }928 private void setScreenSize(WebDriver driver, Integer width, Integer length) {929 driver.manage().window().setPosition(new Point(0, 0));930 driver.manage().window().setSize(new Dimension(width, length));931 }932 private String getScreenSize(WebDriver driver) {933 return driver.manage().window().getSize().width + "*" + driver.manage().window().getSize().height;934 }935 private static String getBaseUrl(String host, String port) {936 String baseurl = "";937 if (!StringUtil.isNullOrEmpty(host) && (host.contains("https://") || host.contains("http://"))) {938 baseurl = host;939 } else {940 baseurl = "http://" + host;941 }942 if (!StringUtil.isNullOrEmpty(port) && Integer.valueOf(port) > 0) {943 baseurl += ":" + port;944 }945 return baseurl;946 }947 private void startRemoteProxy(TestCaseExecution tce) {948 String url = "http://" + tce.getRobotExecutorObj().getHost() + ":" + tce.getRobotExecutorObj().getExecutorExtensionPort() + "/startProxy";949 if (tce.getRobotExecutorObj().getExecutorProxyPort() != 0) {...
getBaseUrl
Using AI Code Generation
1String robotServerBaseUrl = org.cerberus.engine.execution.impl.RobotServerService.getBaseUrl();2String serviceUrl = robotServerBaseUrl + "/GetUser";3String response = org.cerberus.engine.execution.impl.RobotServerService.callService(serviceUrl, "POST", "{}");4System.out.println(response);5org.json.JSONObject responseJson = new org.json.JSONObject(response);6String user = responseJson.getString("user");7System.out.println(user);
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!