Best Cerberus-source code snippet using org.cerberus.crud.entity.TestCaseExecution.getRemoteProxyPort
Source:RobotServerService.java
...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");...
getRemoteProxyPort
Using AI Code Generation
1import org.cerberus.crud.entity.TestCaseExecution;2import org.cerberus.crud.entity.TestCaseStepActionExecution;3import org.cerberus.crud.entity.TestCaseStepExecution;4import org.cerberus.engine.entity.MessageEvent;5import org.cerberus.engine.entity.MessageGeneral;6import org.cerberus.engine.execution.IRecorderService;7import org.cerberus.engine.execution.impl.RecorderService;8import org.cerberus.engine.execution.impl.SikuliService;9import org.cerberus.engine.execution.impl.TestCaseService;10import org.cerberus.engine.execution.impl.TestService;11import org.cerberus.engine.groovy.impl.GroovyVariable;12import org.cerberus.engine.groovy.impl.IGroovyService;13import org.cerberus.engine.groovy.impl.IGroovyVariable;14import org.cerberus.exception.CerberusEventException;15import org.cerberus.util.answer.AnswerItem;16import org.openqa.selenium.Proxy;17import org.openqa.selenium.WebDriver;18import org.openqa.selenium.WebDriverException;19import org.openqa.selenium.remote.CapabilityType;20import org.openqa.selenium.remote.DesiredCapabilities;21import org.openqa.selenium.remote.RemoteWebDriver;22import org.sikuli.script.FindFailed;23import org.sikuli.script.Pattern;24import org.sikuli.script.Screen;25import org.springframework.beans.factory.annotation.Autowired;26import org.springframework.beans.factory.annotation.Qualifier;27import java.net.MalformedURLException;28import java.net.URL;29import java.util.ArrayList;30import java.util.List;31import static java.lang.Thread.sleep;32public class ProxyPort {33 @Qualifier("sikuliService")34 private SikuliService sikuliService;35 @Qualifier("testCaseService")36 private TestCaseService testCaseService;37 @Qualifier("testService")38 private TestService testService;39 @Qualifier("recorderService")40 private RecorderService recorderService;41 @Qualifier("groovyService")42 private IGroovyService groovyService;43 @Qualifier("cerberus_selenium_ip")44 private String cerberus_selenium_ip;45 @Qualifier("cerberus_selenium_port")46 private String cerberus_selenium_port;
getRemoteProxyPort
Using AI Code Generation
1 function getRemoteProxyPort(testCase, testCaseExecution) {2 var remoteProxyPort = 0;3 if (testCaseExecution.getRemoteProxyPort() != null) {4 remoteProxyPort = testCaseExecution.getRemoteProxyPort();5 }6 return remoteProxyPort;7 }8 var remoteProxyPort = getRemoteProxyPort(testCase, testCaseExecution);9 remoteProxyPort;
getRemoteProxyPort
Using AI Code Generation
1import org.cerberus.crud.entity.TestCaseExecution;2TestCaseExecution tce = testCaseExecution;3int remoteProxyPort = tce.getRemoteProxyPort();4RestTemplate restTemplate = new RestTemplate();5HttpHeaders headers = new HttpHeaders();6headers.setContentType(MediaType.APPLICATION_JSON);7HttpEntity<String> entity = new HttpEntity<String>("{\"capabilities\": {\"alwaysMatch\": {\"browserName\": \"chrome\", \"platformName\": \"windows\"}}}", headers);8String response = restTemplate.postForObject(url, entity, String.class);9RestTemplate restTemplate = new RestTemplate();10HttpHeaders headers = new HttpHeaders();11headers.setContentType(MediaType.APPLICATION_JSON);12HttpEntity<String> entity = new HttpEntity<String>("{\"capabilities\": {\"alwaysMatch\": {\"browserName\": \"chrome\", \"platformName\": \"windows\"}}}", headers);13ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);14RestTemplate restTemplate = new RestTemplate();
getRemoteProxyPort
Using AI Code Generation
1import org.cerberus.crud.entity.TestCaseExecution;2import org.cerberus.crud.factory.IFactoryTestCaseExecution;3import java.util.HashMap;4import java.util.Map;5public class GetRemoteProxyURL implements IFactoryTestCaseExecution {6 public TestCaseExecution create(long id, String test, String testCase, String environment, String country, String browser, String browserVersion, String platform, String tag, String verbose, String screenshot, String pageSource, String seleniumLog, String timeout, String manualExecution, String outputFormat, String manualURL, String manualHost, String manualContextRoot, String manualLoginRelativeURL, String manualEnvData, String seleniumIP, String seleniumPort, String description, String usrCreated, String usrModif, String status, String state, String controlStatus, String controlMessage, String controlProperty, String application, String robot, String robotExecutor, String robotHost, String robotPort, String robotPlatform, String robotBrowser, String robotBrowserVersion, String myHost, String myContextRoot, String myLoginRelativeURL, String myEnvData, String battery, String batteryExecutor, String batteryHost, String batteryPort, String screenSize, String userAgent, String verboseExecution, String timeoutInMilliseconds, String pageSource, String screenshot, String seleniumLog, String seleniumIP, String seleniumPort, String seleniumCapabilities, String seleniumCapabilitiesOptions, String seleniumCapabilitiesOptionsArguments, String seleniumCapabilitiesOptionsExtensions, String seleniumCapabilitiesOptionsPrefs, String seleniumCapabilitiesOptionsPrefsInts, String seleniumCapabilitiesOptionsPrefsStrings, String seleniumCapabilities
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!!