Best Cerberus-source code snippet using org.cerberus.engine.execution.impl.RobotServerService.guessRobotProvider
Source:RobotServerService.java  
...176            session.setCerberus_selenium_autoscroll(cerberus_selenium_autoscroll);177            session.setCerberus_selenium_autoscroll_vertical_offset(cerberus_selenium_autoscroll_vertical_offset);178            session.setCerberus_selenium_autoscroll_horizontal_offset(cerberus_selenium_autoscroll_horizontal_offset);179            tCExecution.setSession(session);180            tCExecution.setRobotProvider(guessRobotProvider(session.getHost()));181            LOG.debug("Session is set.");182            /**183             * Starting Cerberus Executor Proxy if it has been activated at184             * robot level.185             */186            if (tCExecution.getRobotExecutorObj() != null && "Y".equals(tCExecution.getRobotExecutorObj().getExecutorProxyActive())) {187                LOG.debug("Start Remote Proxy");188                this.startRemoteProxy(tCExecution);189                LOG.debug("Started Remote Proxy on port:" + tCExecution.getRemoteProxyPort());190            }191            /**192             * SetUp Capabilities193             */194            LOG.debug("Set Capabilities");195            MutableCapabilities caps = this.setCapabilities(tCExecution);196            session.setDesiredCapabilities(caps);197            LOG.debug("Set Capabilities - retreived");198            /**199             * We record Caps list at the execution level.200             */201            try {202                // Init additionalFinalCapabilities and set it from real caps.203                List<RobotCapability> additionalFinalCapabilities = new ArrayList<>();204                for (Map.Entry cap : caps.asMap().entrySet()) {205                    additionalFinalCapabilities.add(factoryRobotCapability.create(0, "", cap.getKey().toString(), cap.getValue().toString()));206                }207                // Init inputCapabilities and set it from Robot values.208                List<RobotCapability> inputCapabilities = new ArrayList<>();209                if (tCExecution.getRobotObj() != null) {210                    inputCapabilities = tCExecution.getRobotObj().getCapabilities();211                }212                tCExecution.addFileList(recorderService.recordCapabilities(tCExecution, inputCapabilities, additionalFinalCapabilities));213            } catch (Exception ex) {214                LOG.error("Exception Saving Robot Caps " + tCExecution.getId() + " Exception :" + ex.toString(), ex);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 CerberusException...guessRobotProvider
Using AI Code Generation
1import com.google.common.base.Strings;2import java.net.MalformedURLException;3import java.net.URL;4import java.util.logging.Level;5import java.util.logging.Logger;6import org.cerberus.engine.entity.MessageEvent;7import org.cerberus.engine.entity.MessageGeneral;8import org.cerberus.engine.entity.Session;9import org.cerberus.engine.execution.IRobotServerService;10import org.cerberus.engine.execution.impl.RobotServerService;11import org.cerberus.exception.CerberusEventException;12import org.cerberus.crud.entity.Robot;13import org.cerberus.crud.entity.RobotProvider;14import org.cerberus.crud.entity.RobotCapability;15import org.cerberus.crud.entity.RobotExecutor;16import org.cerberus.crud.entity.RobotHost;17import org.cerberus.crud.entity.RobotPort;18import org.cerberus.crud.entity.RobotProvider;19import org.cerberus.crud.entity.RobotProviderProperty;20import org.cerberus.crud.entity.RobotProperty;21import org.cerberus.crud.entity.RobotProvider;22import org.cerberus.crud.entity.RobotProviderProperty;23import org.cerberus.crud.entity.RobotProperty;24import org.cerberus.crud.entity.RobotProvider;25import org.cerberus.crud.entity.RobotProviderProperty;26import org.cerberus.crud.entity.RobotProperty;27import org.cerberus.crud.entity.RobotProvider;28import org.cerberus.crud.entity.RobotProviderProperty;29import org.cerberus.crud.entity.RobotProperty;30import org.cerberus.crud.entity.RobotProvider;31import org.cerberus.crudguessRobotProvider
Using AI Code Generation
1import org.cerberus.engine.execution.impl.RobotServerService2import org.cerberus.robot.RobotServerProviderFactory3import org.cerberus.robot.RobotServerProvider4def robotServerService = new RobotServerService()5def robotServerProvider = robotServerService.guessRobotProvider()6if (robotServerProvider == null) {7    robotServerProvider = RobotServerProviderFactory.createRobotServerProvider()8}9robotServerProvider.executeTest("C:\\myRobotTest.robot")10robotServerProvider.stopServer()11import org.cerberus.engine.execution.impl.RobotServerService;12import org.cerberus.robot.RobotServerProviderFactory;13import org.cerberus.robot.RobotServerProvider;14RobotServerService robotServerService = new RobotServerService();15RobotServerProvider robotServerProvider = robotServerService.guessRobotProvider();16if (robotServerProvider == null) {17    robotServerProvider = RobotServerProviderFactory.createRobotServerProvider();18}19robotServerProvider.executeTest("C:\\myRobotTest.robot");20robotServerProvider.stopServer();21import org.cerberus.robot.RobotServerProvider22import org.cerberus.robot.RobotServerProviderFactoryguessRobotProvider
Using AI Code Generation
1def robotProviderType = guessRobotProvider(robotHost, robotPort)2if (robotProviderType == "RobotServer") {3} else if (robotProviderType == "RobotServerSeleniumGrid") {4}5def robot = robotProvider.startRobot(robotHost, robotPort, robotPlatform, robotBrowser, robotVersion, robotCapabilities, robotOptions)6def robot = robotProvider.startRobot(robotHost, robotPort, robotPlatform, robotBrowser, robotVersion, robotCapabilities, robotOptions)7def guessRobotProvider(String robotHost, String robotPort) {8    try {9        def response = new URL(url).getText()10        if (response.contains("Selenium Grid")) {11        }12    } catch (Exception e) {13        LOG.warn("Unable to guess robot provider type for robot " + robotHost + ":" + robotPort + " : " + e.getMessage())14    }15}16def robot = robotProvider.startRobot(robotHost, robotPort, robotPlatform, robotBrowser, robotVersion, robotCapabilities, robotOptions)17def robot = robotProvider.startRobot(robotHost, robotPort, robotPlatform, robotBrowser, robotVersion, robotCapabilities, robotOptions)18def robot = robotProvider.startRobot(robotHostLearn 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!!
