How to use getSeleniumIp method of org.cerberus.crud.entity.Environment class

Best Cerberus-source code snippet using org.cerberus.crud.entity.Environment.getSeleniumIp

Source:SeleniumServerService.java Github

copy

Full Screen

1/**2 * Cerberus Copyright (C) 2013 - 2017 cerberustesting3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.4 *5 * This file is part of Cerberus.6 *7 * Cerberus is free software: you can redistribute it and/or modify8 * it under the terms of the GNU General Public License as published by9 * the Free Software Foundation, either version 3 of the License, or10 * (at your option) any later version.11 *12 * Cerberus is distributed in the hope that it will be useful,13 * but WITHOUT ANY WARRANTY; without even the implied warranty of14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the15 * GNU General Public License for more details.16 *17 * You should have received a copy of the GNU General Public License18 * along with Cerberus. If not, see <http://www.gnu.org/licenses/>.19 */20package org.cerberus.engine.execution.impl;21import io.appium.java_client.AppiumDriver;22import io.appium.java_client.android.AndroidDriver;23import io.appium.java_client.ios.IOSDriver;24import java.io.IOException;25import java.io.InputStream;26import java.io.StringWriter;27import java.net.MalformedURLException;28import java.net.URL;29import java.util.HashMap;30import java.util.List;31import java.util.concurrent.TimeUnit;32import org.apache.commons.io.IOUtils;33import org.apache.http.HttpHost;34import org.apache.http.HttpResponse;35import org.apache.http.auth.AuthScope;36import org.apache.http.auth.UsernamePasswordCredentials;37import org.apache.http.client.CredentialsProvider;38import org.apache.http.client.HttpClient;39import org.apache.http.impl.client.BasicCredentialsProvider;40import org.apache.http.impl.client.HttpClientBuilder;41import org.apache.http.impl.client.LaxRedirectStrategy;42import org.apache.http.message.BasicHttpEntityEnclosingRequest;43import org.apache.logging.log4j.LogManager;44import org.apache.logging.log4j.Logger;45import org.cerberus.crud.entity.Application;46import org.cerberus.crud.entity.Invariant;47import org.cerberus.engine.entity.MessageGeneral;48import org.cerberus.crud.entity.RobotCapability;49import org.cerberus.engine.entity.Session;50import org.cerberus.crud.entity.TestCaseExecution;51import org.cerberus.crud.service.IInvariantService;52import org.cerberus.crud.service.IParameterService;53import org.cerberus.enums.MessageGeneralEnum;54import org.cerberus.exception.CerberusException;55import org.cerberus.engine.execution.ISeleniumServerService;56import org.cerberus.service.proxy.IProxyService;57import org.cerberus.service.sikuli.ISikuliService;58import org.cerberus.util.StringUtil;59import org.json.JSONException;60import org.json.JSONObject;61import org.openqa.selenium.Capabilities;62import org.openqa.selenium.Dimension;63import org.openqa.selenium.JavascriptExecutor;64import org.openqa.selenium.Platform;65import org.openqa.selenium.Point;66import org.openqa.selenium.WebDriver;67import org.openqa.selenium.chrome.ChromeOptions;68import org.openqa.selenium.firefox.FirefoxDriver;69import org.openqa.selenium.firefox.FirefoxProfile;70import org.openqa.selenium.remote.BrowserType;71import org.openqa.selenium.remote.CommandInfo;72import org.openqa.selenium.remote.DesiredCapabilities;73import org.openqa.selenium.remote.HttpCommandExecutor;74import org.openqa.selenium.remote.RemoteWebDriver;75import org.openqa.selenium.remote.SessionId;76import org.openqa.selenium.remote.UnreachableBrowserException;77import org.openqa.selenium.remote.http.HttpClient.Factory;78import org.springframework.beans.factory.annotation.Autowired;79import org.springframework.stereotype.Service;80/**81 *82 * @author bcivel83 */84@Service85public class SeleniumServerService implements ISeleniumServerService {86 @Autowired87 private IParameterService parameterService;88 @Autowired89 private IInvariantService invariantService;90 @Autowired91 private ISikuliService sikuliService;92 @Autowired93 IProxyService proxyService;94 private static final Logger LOG = LogManager.getLogger(SeleniumServerService.class);95 /**96 * Proxy default config. (Should never be used as default config is inserted97 * into database)98 */99 private static final boolean DEFAULT_PROXY_ACTIVATE = false;100 private static final String DEFAULT_PROXY_HOST = "proxy";101 private static final int DEFAULT_PROXY_PORT = 80;102 private static final boolean DEFAULT_PROXYAUTHENT_ACTIVATE = false;103 private static final String DEFAULT_PROXYAUTHENT_USER = "squid";104 private static final String DEFAULT_PROXYAUTHENT_PASSWORD = "squid";105 @Override106 public void startServer(TestCaseExecution tCExecution) throws CerberusException {107 //message used for log purposes 108 String logPrefix = "[" + tCExecution.getTest() + " - " + tCExecution.getTestCase() + "] ";109 try {110 LOG.info(logPrefix + "Start Robot Server (Selenium, Appium or Sikuli)");111 /**112 * Set Session113 */114 LOG.debug(logPrefix + "Setting the session.");115 String system = tCExecution.getApplicationObj().getSystem();116 /**117 * Get the parameters that will be used to set the servers118 * (selenium/appium) If timeout has been defined at the execution119 * level, set the selenium & appium wait element with this value,120 * else, take the one from parameter121 */122 Integer cerberus_selenium_pageLoadTimeout, cerberus_selenium_implicitlyWait, cerberus_selenium_setScriptTimeout, cerberus_selenium_wait_element, cerberus_appium_wait_element, cerberus_selenium_action_click_timeout;123 if (!tCExecution.getTimeout().isEmpty()) {124 cerberus_selenium_wait_element = Integer.valueOf(tCExecution.getTimeout());125 cerberus_appium_wait_element = Integer.valueOf(tCExecution.getTimeout());126 } else {127 cerberus_selenium_wait_element = parameterService.getParameterIntegerByKey("cerberus_selenium_wait_element", system, 90000);128 cerberus_appium_wait_element = parameterService.getParameterIntegerByKey("cerberus_appium_wait_element", system, 90000);129 }130 cerberus_selenium_pageLoadTimeout = parameterService.getParameterIntegerByKey("cerberus_selenium_pageLoadTimeout", system, 90000);131 cerberus_selenium_implicitlyWait = parameterService.getParameterIntegerByKey("cerberus_selenium_implicitlyWait", system, 0);132 cerberus_selenium_setScriptTimeout = parameterService.getParameterIntegerByKey("cerberus_selenium_setScriptTimeout", system, 90000);133 cerberus_selenium_action_click_timeout = parameterService.getParameterIntegerByKey("cerberus_selenium_action_click_timeout", system, 90000);134 LOG.debug(logPrefix + "TimeOut defined on session : " + cerberus_selenium_wait_element);135 Session session = new Session();136 session.setCerberus_selenium_implicitlyWait(cerberus_selenium_implicitlyWait);137 session.setCerberus_selenium_pageLoadTimeout(cerberus_selenium_pageLoadTimeout);138 session.setCerberus_selenium_setScriptTimeout(cerberus_selenium_setScriptTimeout);139 session.setCerberus_selenium_wait_element(cerberus_selenium_wait_element);140 session.setCerberus_appium_wait_element(cerberus_appium_wait_element);141 session.setCerberus_selenium_action_click_timeout(cerberus_selenium_action_click_timeout);142 session.setHost(tCExecution.getSeleniumIP());143 session.setHostUser(tCExecution.getSeleniumIPUser());144 session.setHostPassword(tCExecution.getSeleniumIPPassword());145 session.setPort(tCExecution.getPort());146 tCExecution.setSession(session);147 LOG.debug(logPrefix + "Session is set.");148 /**149 * SetUp Capabilities150 */151 LOG.debug(logPrefix + "Set Capabilities");152 DesiredCapabilities caps = this.setCapabilities(tCExecution);153 session.setDesiredCapabilities(caps);154 LOG.debug(logPrefix + "Set Capabilities - retreived");155 /**156 * SetUp Proxy157 */158 String hubUrl = StringUtil.cleanHostURL(159 SeleniumServerService.getBaseUrl(StringUtil.formatURLCredential(160 tCExecution.getSession().getHostUser(),161 tCExecution.getSession().getHostPassword()) + session.getHost(),162 session.getPort())) + "/wd/hub";163 LOG.debug(logPrefix + "Hub URL :" + hubUrl);164 URL url = new URL(hubUrl);165 HttpCommandExecutor executor = null;166 boolean isProxy = proxyService.useProxy(hubUrl, system);167 if (isProxy) {168 String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", system, DEFAULT_PROXY_HOST);169 int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", system, DEFAULT_PROXY_PORT);170 HttpClientBuilder builder = HttpClientBuilder.create();171 HttpHost proxy = new HttpHost(proxyHost, proxyPort);172 builder.setProxy(proxy);173 if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system, DEFAULT_PROXYAUTHENT_ACTIVATE)) {174 String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", system, DEFAULT_PROXYAUTHENT_USER);175 String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", system, DEFAULT_PROXYAUTHENT_PASSWORD);176 CredentialsProvider credsProvider = new BasicCredentialsProvider();177 credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));178 if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {179 credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())), new UsernamePasswordCredentials(url.getUserInfo()));180 }181 builder.setDefaultCredentialsProvider(credsProvider);182 }183 Factory factory = new MyHttpClientFactory(builder);184 executor = new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory);185 }186 /**187 * SetUp Driver188 */189 LOG.debug(logPrefix + "Set Driver");190 WebDriver driver = null;191 AppiumDriver appiumDriver = null;192 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI)) {193 if (caps.getPlatform().is(Platform.ANDROID)) {194 if (executor == null) {195 appiumDriver = new AndroidDriver(url, caps);196 } else {197 appiumDriver = new AndroidDriver(executor, caps);198 }199 driver = (WebDriver) appiumDriver;200 } else if (caps.getPlatform().is(Platform.MAC)) {201 if (executor == null) {202 appiumDriver = new IOSDriver(url, caps);203 } else {204 appiumDriver = new IOSDriver(executor, caps);205 }206 driver = (WebDriver) appiumDriver;207 } else // Any Other208 {209 if (executor == null) {210 driver = new RemoteWebDriver(url, caps);211 } else {212 driver = new RemoteWebDriver(executor, caps);213 }214 }215 } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)) {216 if (executor == null) {217 appiumDriver = new AndroidDriver(url, caps);218 } else {219 appiumDriver = new AndroidDriver(executor, caps);220 }221 driver = (WebDriver) appiumDriver;222 } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_IPA)) {223 if (executor == null) {224 appiumDriver = new IOSDriver(url, caps);225 } else {226 appiumDriver = new IOSDriver(executor, caps);227 }228 driver = (WebDriver) appiumDriver;229 } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_FAT)) {230 /**231 * Check sikuli extension is reachable232 */233 if (!sikuliService.isSikuliServerReachable(session)) {234 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SIKULI_COULDNOTCONNECT);235 mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));236 mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));237 throw new CerberusException(mes);238 }239 /**240 * If CountryEnvParameter IP is set, open the App241 */242 if (!tCExecution.getCountryEnvironmentParameters().getIp().isEmpty()) {243 sikuliService.doSikuliActionOpenApp(session, tCExecution.getCountryEnvironmentParameters().getIp());244 }245 }246 /**247 * Defining the timeout at the driver level. Only in case of not248 * Appium Driver (see249 * https://github.com/vertigo17/Cerberus/issues/754)250 */251 if (driver != null && appiumDriver == null) {252 driver.manage().timeouts().pageLoadTimeout(cerberus_selenium_pageLoadTimeout, TimeUnit.MILLISECONDS);253 driver.manage().timeouts().implicitlyWait(cerberus_selenium_implicitlyWait, TimeUnit.MILLISECONDS);254 driver.manage().timeouts().setScriptTimeout(cerberus_selenium_setScriptTimeout, TimeUnit.MILLISECONDS);255 }256 tCExecution.getSession().setDriver(driver);257 tCExecution.getSession().setAppiumDriver(appiumDriver);258 /**259 * If Gui application, maximize window Get IP of Node in case of260 * remote Server. Maximize does not work for chrome browser We also261 * get the Real UserAgent from the browser.262 */263 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI)264 && !caps.getPlatform().equals(Platform.ANDROID)) {265 if (!caps.getBrowserName().equals(BrowserType.CHROME)) {266 driver.manage().window().maximize();267 }268 getIPOfNode(tCExecution);269 /**270 * If screenSize is defined, set the size of the screen.271 */272 String targetScreensize = getScreenSizeToUse(tCExecution.getTestCaseObj().getScreenSize(), tCExecution.getScreenSize());273 LOG.debug("Selenium resolution : " + targetScreensize);274 if ((!StringUtil.isNullOrEmpty(targetScreensize)) && targetScreensize.contains("*")) {275 Integer screenWidth = Integer.valueOf(targetScreensize.split("\\*")[0]);276 Integer screenLength = Integer.valueOf(targetScreensize.split("\\*")[1]);277 setScreenSize(driver, screenWidth, screenLength);278 LOG.debug("Selenium resolution Activated : " + screenWidth + "*" + screenLength);279 }280 tCExecution.setScreenSize(getScreenSize(driver));281 tCExecution.setRobotDecli(tCExecution.getRobotDecli().replace("%SCREENSIZE%", tCExecution.getScreenSize()));282 String userAgent = (String) ((JavascriptExecutor) driver).executeScript("return navigator.userAgent;");283 tCExecution.setUserAgent(userAgent);284 }285 tCExecution.getSession().setStarted(true);286 } catch (CerberusException exception) {287 LOG.error(logPrefix + exception.toString(), exception);288 throw new CerberusException(exception.getMessageError());289 } catch (MalformedURLException exception) {290 LOG.error(logPrefix + exception.toString(), exception);291 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_URL_MALFORMED);292 mes.setDescription(mes.getDescription().replace("%URL%", tCExecution.getSession().getHost() + ":" + tCExecution.getSession().getPort()));293 throw new CerberusException(mes);294 } catch (UnreachableBrowserException exception) {295 LOG.error(logPrefix + exception.toString(), exception);296 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SELENIUM_COULDNOTCONNECT);297 mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));298 mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));299 mes.setDescription(mes.getDescription().replace("%ERROR%", exception.toString()));300 throw new CerberusException(mes);301 } catch (Exception exception) {302 LOG.error(logPrefix + exception.toString(), exception);303 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);304 mes.setDescription(mes.getDescription().replace("%MES%", exception.toString()));305 throw new CerberusException(mes);306 }307 }308 /**309 * Set DesiredCapabilities310 *311 * @param tCExecution312 * @return313 * @throws CerberusException314 */315 private DesiredCapabilities setCapabilities(TestCaseExecution tCExecution) throws CerberusException {316 /**317 * Instanciate DesiredCapabilities318 */319 DesiredCapabilities caps = new DesiredCapabilities();320 // In case browser is not defined at that level, we force it to firefox.321 if (StringUtil.isNullOrEmpty(tCExecution.getBrowser())) {322 tCExecution.setBrowser("firefox");323 }324 caps = this.setCapabilityBrowser(caps, tCExecution.getBrowser(), tCExecution);325 /**326 * Feed DesiredCapabilities with values get from Robot327 */328 if (!StringUtil.isNullOrEmpty(tCExecution.getPlatform())) {329 caps.setCapability("platform", tCExecution.getPlatform());330 }331 if (!StringUtil.isNullOrEmpty(tCExecution.getVersion())) {332 caps.setCapability("version", tCExecution.getVersion());333 }334 /**335 * Loop on RobotCapabilities to feed DesiredCapabilities Capability must336 * be String, Integer or Boolean337 */338 List<RobotCapability> additionalCapabilities = tCExecution.getCapabilities();339 if (additionalCapabilities != null) {340 for (RobotCapability additionalCapability : additionalCapabilities) {341 if (StringUtil.isBoolean(additionalCapability.getValue())) {342 caps.setCapability(additionalCapability.getCapability(), StringUtil.parseBoolean(additionalCapability.getValue()));343 } else if (StringUtil.isInteger(additionalCapability.getValue())) {344 caps.setCapability(additionalCapability.getCapability(), Integer.valueOf(additionalCapability.getValue()));345 } else {346 caps.setCapability(additionalCapability.getCapability(), additionalCapability.getValue());347 }348 }349 }350 /**351 * if application is a mobile one, then set the "app" capability to the352 * application binary path353 */354 if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)355 || tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_IPA)) {356 // Set the app capability with the application path357 if (tCExecution.isManualURL()) {358 caps.setCapability("app", tCExecution.getMyHost());359 } else {360 caps.setCapability("app", tCExecution.getCountryEnvironmentParameters().getIp());361 }362 }363 return caps;364 }365 /**366 * Instanciate DesiredCapabilities regarding the browser367 *368 * @param capabilities369 * @param browser370 * @param tCExecution371 * @return372 * @throws CerberusException373 */374 private DesiredCapabilities setCapabilityBrowser(DesiredCapabilities capabilities, String browser, TestCaseExecution tCExecution) throws CerberusException {375 try {376 if (browser.equalsIgnoreCase("firefox")) {377 capabilities = DesiredCapabilities.firefox();378 FirefoxProfile profile = new FirefoxProfile();379 profile.setPreference("app.update.enabled", false);380 try {381 Invariant invariant = invariantService.convert(invariantService.readByKey("COUNTRY", tCExecution.getCountry()));382 if (invariant.getGp2() == null) {383 LOG.warn("Country selected (" + tCExecution.getCountry() + ") has no value of GP2 in Invariant table, default language set to English (en)");384 profile.setPreference("intl.accept_languages", "en");385 } else {386 profile.setPreference("intl.accept_languages", invariant.getGp2());387 }388 } catch (CerberusException ex) {389 LOG.warn("Country selected (" + tCExecution.getCountry() + ") not in Invariant table, default language set to English (en)");390 profile.setPreference("intl.accept_languages", "en");391 }392 // Set UserAgent if testCaseUserAgent or robotUserAgent is defined393 String usedUserAgent = getUserAgentToUse(tCExecution.getTestCaseObj().getUserAgent(), tCExecution.getUserAgent());394 if (!StringUtil.isNullOrEmpty(usedUserAgent)) {395 profile.setPreference("general.useragent.override", usedUserAgent);396 }397 capabilities.setCapability(FirefoxDriver.PROFILE, profile);398 } else if (browser.equalsIgnoreCase("IE")) {399 capabilities = DesiredCapabilities.internetExplorer();400 } else if (browser.equalsIgnoreCase("chrome")) {401 capabilities = DesiredCapabilities.chrome();402 /**403 * Add custom capabilities404 */405 ChromeOptions options = new ChromeOptions();406 // Maximize windows for chrome browser407 options.addArguments("--start-fullscreen");408 // Set UserAgent if necessary409 String usedUserAgent = getUserAgentToUse(tCExecution.getTestCaseObj().getUserAgent(), tCExecution.getUserAgent());410 if (!StringUtil.isNullOrEmpty(usedUserAgent)) {411 options.addArguments("--user-agent=" + usedUserAgent);412 }413 capabilities.setCapability(ChromeOptions.CAPABILITY, options);414 } else if (browser.contains("android")) {415 capabilities = DesiredCapabilities.android();416 } else if (browser.contains("ipad")) {417 capabilities = DesiredCapabilities.ipad();418 } else if (browser.contains("iphone")) {419 capabilities = DesiredCapabilities.iphone();420 } else if (browser.contains("opera")) {421 capabilities = DesiredCapabilities.opera();422 } else if (browser.contains("safari")) {423 capabilities = DesiredCapabilities.safari();424 } else {425 LOG.warn("Not supported Browser : " + browser);426 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);427 mes.setDescription(mes.getDescription().replace("%MES%", "Browser '" + browser + "' is not supported"));428 mes.setDescription("Not supported Browser : " + browser);429 throw new CerberusException(mes);430 }431 } catch (CerberusException ex) {432 MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);433 mes.setDescription(mes.getDescription().replace("%MES%", "Failed to set capability on the browser '" + browser + "' due to " + ex.getMessageError().getDescription()));434 throw new CerberusException(mes);435 }436 return capabilities;437 }438 /**439 * This method determine which user agent to use.440 *441 * @param userAgentTestCase442 * @param userAgentRobot443 * @return String containing the userAgent to use444 */445 private String getUserAgentToUse(String userAgentTestCase, String userAgentRobot) {446 if (StringUtil.isNullOrEmpty(userAgentRobot) && StringUtil.isNullOrEmpty(userAgentTestCase)) {447 return "";448 } else {449 return StringUtil.isNullOrEmpty(userAgentTestCase) ? userAgentRobot : userAgentTestCase;450 }451 }452 /**453 * This method determine which screenSize to use.454 *455 * @param screenSizeTestCase456 * @param screenSizeRobot457 * @return String containing the userAgent to use458 */459 private String getScreenSizeToUse(String screenSizeTestCase, String screenSizeRobot) {460 if (StringUtil.isNullOrEmpty(screenSizeRobot) && StringUtil.isNullOrEmpty(screenSizeTestCase)) {461 return "";462 } else {463 return StringUtil.isNullOrEmpty(screenSizeTestCase) ? screenSizeRobot : screenSizeTestCase;464 }465 }466 @Override467 public boolean stopServer(Session session) {468 if (session.isStarted()) {469 try {470 // Wait 2 sec till HAR is exported471 Thread.sleep(2000);472 } catch (InterruptedException ex) {473 LOG.error(ex.toString());474 }475 LOG.info("Stop execution session");476 session.quit();477 return true;478 }479 return false;480 }481 private static void getIPOfNode(TestCaseExecution tCExecution) {482 try {483 Session session = tCExecution.getSession();484 HttpCommandExecutor ce = (HttpCommandExecutor) ((RemoteWebDriver) session.getDriver()).getCommandExecutor();485 SessionId sessionId = ((RemoteWebDriver) session.getDriver()).getSessionId();486 String hostName = ce.getAddressOfRemoteServer().getHost();487 int port = ce.getAddressOfRemoteServer().getPort();488 HttpHost host = new HttpHost(hostName, port);489 HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();490 URL sessionURL = new URL(SeleniumServerService.getBaseUrl(session.getHost(), session.getPort()) + "/grid/api/testsession?session=" + sessionId);491 BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());492 HttpResponse response = client.execute(host, r);493 if (!response.getStatusLine().toString().contains("403")494 && !response.getEntity().getContentType().getValue().contains("text/html")) {495 InputStream contents = response.getEntity().getContent();496 StringWriter writer = new StringWriter();497 IOUtils.copy(contents, writer, "UTF8");498 JSONObject object = new JSONObject(writer.toString());499 URL myURL = new URL(object.getString("proxyId"));500 if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {501 tCExecution.setIp(myURL.getHost());502 tCExecution.setPort(String.valueOf(myURL.getPort()));503 }504 }505 } catch (IOException ex) {506 LOG.error(ex.toString());507 } catch (JSONException ex) {508 LOG.error(ex.toString());509 }510 }511 @Override512 public Capabilities getUsedCapabilities(Session session) {513 Capabilities caps = ((RemoteWebDriver) session.getDriver()).getCapabilities();514 return caps;515 }516 private void setScreenSize(WebDriver driver, Integer width, Integer length) {517 driver.manage().window().setPosition(new Point(0, 0));518 driver.manage().window().setSize(new Dimension(width, length));519 }520 private String getScreenSize(WebDriver driver) {521 return driver.manage().window().getSize().width + "*" + driver.manage().window().getSize().height;522 }523 private static String getBaseUrl(String host, String port) {524 String baseurl = "";525 if (!StringUtil.isNullOrEmpty(host) && (host.contains("https://") || host.contains("http://"))) {526 baseurl = host;527 } else {528 baseurl = "http://" + host;529 }530 if (!StringUtil.isNullOrEmpty(port) && Integer.valueOf(port) > 0) {531 baseurl += ":" + port;532 }533 return baseurl;534 }535}...

Full Screen

Full Screen

Source:ReadCerberusDetailInformation.java Github

copy

Full Screen

1/**2 * Cerberus Copyright (C) 2013 - 2017 cerberustesting3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.4 *5 * This file is part of Cerberus.6 *7 * Cerberus is free software: you can redistribute it and/or modify8 * it under the terms of the GNU General Public License as published by9 * the Free Software Foundation, either version 3 of the License, or10 * (at your option) any later version.11 *12 * Cerberus is distributed in the hope that it will be useful,13 * but WITHOUT ANY WARRANTY; without even the implied warranty of14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the15 * GNU General Public License for more details.16 *17 * You should have received a copy of the GNU General Public License18 * along with Cerberus. If not, see <http://www.gnu.org/licenses/>.19 */20package org.cerberus.servlet.information;21import java.io.IOException;22import java.sql.Timestamp;23import java.util.HashMap;24import javax.servlet.ServletException;25import javax.servlet.annotation.WebServlet;26import javax.servlet.http.HttpServlet;27import javax.servlet.http.HttpServletRequest;28import javax.servlet.http.HttpServletResponse;29import org.apache.logging.log4j.LogManager;30import org.apache.logging.log4j.Logger;31import org.cerberus.database.dao.ICerberusInformationDAO;32import org.cerberus.engine.entity.ExecutionUUID;33import org.cerberus.crud.entity.SessionCounter;34import org.cerberus.crud.entity.TestCaseExecution;35import org.cerberus.crud.service.IMyVersionService;36import org.cerberus.database.IDatabaseVersioningService;37import org.cerberus.util.answer.AnswerItem;38import org.cerberus.version.Infos;39import org.json.JSONArray;40import org.json.JSONException;41import org.json.JSONObject;42import org.springframework.context.ApplicationContext;43import org.springframework.web.context.support.WebApplicationContextUtils;44/**45 *46 * @author bcivel47 */48@WebServlet(name = "ReadCerberusDetailInformation", urlPatterns = {"/ReadCerberusDetailInformation"})49public class ReadCerberusDetailInformation extends HttpServlet {50 private static final Logger LOG = LogManager.getLogger(ReadCerberusDetailInformation.class);51 52 private ICerberusInformationDAO cerberusDatabaseInformation;53 private IDatabaseVersioningService databaseVersionService;54 private IMyVersionService myVersionService;55 /**56 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>57 * methods.58 *59 * @param request servlet request60 * @param response servlet response61 * @throws ServletException if a servlet-specific error occurs62 * @throws IOException if an I/O error occurs63 */64 protected void processRequest(HttpServletRequest request, HttpServletResponse response)65 throws ServletException, IOException {66 JSONObject jsonResponse = new JSONObject();67 ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());68 ExecutionUUID euuid = appContext.getBean(ExecutionUUID.class);69 SessionCounter sc = appContext.getBean(SessionCounter.class);70 Infos infos = new Infos();71 try {72 jsonResponse.put("simultaneous_execution", euuid.size());73 JSONArray executionArray = new JSONArray();74 for (Object ex : euuid.getExecutionUUIDList().values()) {75 TestCaseExecution execution = (TestCaseExecution) ex;76 JSONObject object = new JSONObject();77 object.put("id", execution.getId());78 object.put("test", execution.getTest());79 object.put("testcase", execution.getTestCase());80 object.put("system", execution.getApplicationObj().getSystem());81 object.put("application", execution.getApplication());82 object.put("environment", execution.getEnvironmentData());83 object.put("country", execution.getCountry());84 object.put("robotIP", execution.getSeleniumIP());85 object.put("tag", execution.getTag());86 object.put("start", new Timestamp(execution.getStart()));87 executionArray.put(object);88 }89 jsonResponse.put("simultaneous_execution_list", executionArray);90 jsonResponse.put("simultaneous_session", sc.getTotalActiveSession());91 jsonResponse.put("active_users", sc.getActiveUsers());92 cerberusDatabaseInformation = appContext.getBean(ICerberusInformationDAO.class);93 AnswerItem ans = cerberusDatabaseInformation.getDatabaseInformation();94 HashMap<String, String> cerberusInformation = (HashMap<String, String>) ans.getItem();95 // Database Informations.96 jsonResponse.put("DatabaseProductName", cerberusInformation.get("DatabaseProductName"));97 jsonResponse.put("DatabaseProductVersion", cerberusInformation.get("DatabaseProductVersion"));98 jsonResponse.put("DatabaseMajorVersion", cerberusInformation.get("DatabaseMajorVersion"));99 jsonResponse.put("DatabaseMinorVersion", cerberusInformation.get("DatabaseMinorVersion"));100 jsonResponse.put("DriverName", cerberusInformation.get("DriverName"));101 jsonResponse.put("DriverVersion", cerberusInformation.get("DriverVersion"));102 jsonResponse.put("DriverMajorVersion", cerberusInformation.get("DriverMajorVersion"));103 jsonResponse.put("DriverMinorVersion", cerberusInformation.get("DriverMinorVersion"));104 jsonResponse.put("JDBCMajorVersion", cerberusInformation.get("JDBCMajorVersion"));105 jsonResponse.put("JDBCMinorVersion", cerberusInformation.get("JDBCMinorVersion"));106 // Cerberus Informations.107 jsonResponse.put("projectName", infos.getProjectName());108 jsonResponse.put("projectVersion", infos.getProjectVersion());109 jsonResponse.put("environment", System.getProperty("org.cerberus.environment"));110 databaseVersionService = appContext.getBean(IDatabaseVersioningService.class);111 jsonResponse.put("databaseCerberusTargetVersion", databaseVersionService.getSQLScript().size());112 myVersionService = appContext.getBean(IMyVersionService.class);113 if (myVersionService.findMyVersionByKey("database") != null) {114 jsonResponse.put("databaseCerberusCurrentVersion", myVersionService.findMyVersionByKey("database").getValue());115 } else {116 jsonResponse.put("databaseCerberusCurrentVersion", "0");117 }118 // JAVA Informations.119 jsonResponse.put("javaVersion", System.getProperty("java.version"));120 Runtime instance = Runtime.getRuntime();121 int mb = 1024 * 1024;122 jsonResponse.put("javaFreeMemory", instance.freeMemory() / mb);123 jsonResponse.put("javaTotalMemory", instance.totalMemory() / mb);124 jsonResponse.put("javaUsedMemory", (instance.totalMemory() - instance.freeMemory()) / mb);125 jsonResponse.put("javaMaxMemory", instance.maxMemory() / mb);126 String str1 = getServletContext().getServerInfo();127 jsonResponse.put("applicationServerInfo", str1);128 } catch (JSONException ex) {129 LOG.warn(ex);130 }131 response.setContentType("application/json");132 response.getWriter().print(jsonResponse.toString());133 }134 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">135 /**136 * Handles the HTTP <code>GET</code> method.137 *138 * @param request servlet request139 * @param response servlet response140 * @throws ServletException if a servlet-specific error occurs141 * @throws IOException if an I/O error occurs142 */143 @Override144 protected void doGet(HttpServletRequest request, HttpServletResponse response)145 throws ServletException, IOException {146 processRequest(request, response);147 }148 /**149 * Handles the HTTP <code>POST</code> method.150 *151 * @param request servlet request152 * @param response servlet response153 * @throws ServletException if a servlet-specific error occurs154 * @throws IOException if an I/O error occurs155 */156 @Override157 protected void doPost(HttpServletRequest request, HttpServletResponse response)158 throws ServletException, IOException {159 processRequest(request, response);160 }161 /**162 * Returns a short description of the servlet.163 *164 * @return a String containing servlet description165 */166 @Override167 public String getServletInfo() {168 return "Short description";169 }// </editor-fold>170}...

Full Screen

Full Screen

Source:Environment.java Github

copy

Full Screen

...82 }83 public void setTypeApplication(String tempTypeApplication) {84 this.typeApplication = tempTypeApplication;85 }86 public String getSeleniumIp() {87 return this.seleniumIp;88 }89 public void setSeleniumIp(String seleniumIp) {90 this.seleniumIp = seleniumIp;91 }92 public String getSeleniumPort() {93 return this.seleniumPort;94 }95 public void setSeleniumPort(String seleniumPort) {96 this.seleniumPort = seleniumPort;97 }98 public String getSeleniumBrowser() {99 return this.seleniumBrowser;100 }...

Full Screen

Full Screen

getSeleniumIp

Using AI Code Generation

copy

Full Screen

1Environment env = new Environment();2String seleniumIp = env.getSeleniumIp();3Environment env = new Environment();4String seleniumIp = env.getSeleniumIp();5Environment env = new Environment();6String seleniumIp = env.getSeleniumIp();7Environment env = new Environment();8String seleniumIp = env.getSeleniumIp();9Environment env = new Environment();10String seleniumIp = env.getSeleniumIp();11Environment env = new Environment();12String seleniumIp = env.getSeleniumIp();13Environment env = new Environment();14String seleniumIp = env.getSeleniumIp();15Environment env = new Environment();16String seleniumIp = env.getSeleniumIp();17Environment env = new Environment();18String seleniumIp = env.getSeleniumIp();19Environment env = new Environment();20String seleniumIp = env.getSeleniumIp();21Environment env = new Environment();22String seleniumIp = env.getSeleniumIp();23Environment env = new Environment();24String seleniumIp = env.getSeleniumIp();

Full Screen

Full Screen

getSeleniumIp

Using AI Code Generation

copy

Full Screen

1Environment env = new Environment();2String seleniumIp = env.getSeleniumIp();3System.out.println(seleniumIp);4Environment env = new Environment();5String seleniumIp = env.getSeleniumIp();6System.out.println(seleniumIp);7Environment env = new Environment();8String seleniumIp = env.getSeleniumIp();9System.out.println(seleniumIp);10Environment env = new Environment();11String seleniumIp = env.getSeleniumIp();12System.out.println(seleniumIp);13Environment env = new Environment();14String seleniumIp = env.getSeleniumIp();15System.out.println(seleniumIp);16Environment env = new Environment();17String seleniumIp = env.getSeleniumIp();18System.out.println(seleniumIp);19Environment env = new Environment();20String seleniumIp = env.getSeleniumIp();21System.out.println(seleniumIp);22Environment env = new Environment();23String seleniumIp = env.getSeleniumIp();24System.out.println(seleniumIp);25Environment env = new Environment();26String seleniumIp = env.getSeleniumIp();27System.out.println(seleniumIp);28Environment env = new Environment();29String seleniumIp = env.getSeleniumIp();30System.out.println(seleniumIp);31Environment env = new Environment();

Full Screen

Full Screen

getSeleniumIp

Using AI Code Generation

copy

Full Screen

1String seleniumIp = myEnvironment.getSeleniumIp();2String robotIp = myEnvironment.getRobotIp();3String robotPort = myEnvironment.getRobotPort();4String robotPlatform = myEnvironment.getRobotPlatform();5String robotBrowser = myEnvironment.getRobotBrowser();6String robotVersion = myEnvironment.getRobotVersion();7String robotHost = myEnvironment.getRobotHost();8String robotPort = myEnvironment.getRobotPort();9String robotPlatform = myEnvironment.getRobotPlatform();10String robotBrowser = myEnvironment.getRobotBrowser();11String robotVersion = myEnvironment.getRobotVersion();12String robotHost = myEnvironment.getRobotHost();13String robotPort = myEnvironment.getRobotPort();14String robotPlatform = myEnvironment.getRobotPlatform();

Full Screen

Full Screen

getSeleniumIp

Using AI Code Generation

copy

Full Screen

1Environment env = new Environment();2env.setSeleniumIP("localhost");3env.setSeleniumPort("4444");4String seleniumIp = env.getSeleniumIP();5String seleniumPort = env.getSeleniumPort();6Environment env = new Environment();7env.setSeleniumIP("localhost");8env.setSeleniumPort("4444");9String seleniumIp = env.getSeleniumIP();10String seleniumPort = env.getSeleniumPort();11Environment env = new Environment();12env.setSeleniumIP("localhost");13env.setSeleniumPort("4444");14String seleniumIp = env.getSeleniumIP();15String seleniumPort = env.getSeleniumPort();16Environment env = new Environment();17env.setSeleniumIP("localhost");18env.setSeleniumPort("4444");19String seleniumIp = env.getSeleniumIP();20String seleniumPort = env.getSeleniumPort();21Environment env = new Environment();22env.setSeleniumIP("localhost");23env.setSeleniumPort("4444");24String seleniumIp = env.getSeleniumIP();25String seleniumPort = env.getSeleniumPort();26Environment env = new Environment();27env.setSeleniumIP("localhost");28env.setSeleniumPort("4444");29String seleniumIp = env.getSeleniumIP();30String seleniumPort = env.getSeleniumPort();31Environment env = new Environment();32env.setSeleniumIP("localhost");33env.setSeleniumPort("4444");34String seleniumIp = env.getSeleniumIP();35String seleniumPort = env.getSeleniumPort();36Environment env = new Environment();37env.setSeleniumIP("localhost");38env.setSeleniumPort("4444");39String seleniumIp = env.getSeleniumIP();40String seleniumPort = env.getSeleniumPort();41Environment env = new Environment();

Full Screen

Full Screen

getSeleniumIp

Using AI Code Generation

copy

Full Screen

1package com.cerberus.test;2import org.cerberus.crud.entity.Environment;3public class test {4 public static void main(String[] args) {5 Environment env = new Environment();6 env.setSeleniumIP("localhost");7 System.out.println(env.getSeleniumIP());8 }9}10package com.cerberus.test;11import org.cerberus.crud.entity.Environment;12public class test {13 public static void main(String[] args) {14 Environment env = new Environment();15 env.setIp("

Full Screen

Full Screen

getSeleniumIp

Using AI Code Generation

copy

Full Screen

1import org.cerberus.crud.entity.Environment;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.chrome.ChromeOptions;7import org.openqa.selenium.remote.RemoteWebDriver;8import org.openqa.selenium.remote.DesiredCapabilities;9import java.net.MalformedURLException;10import java.net.URL;11import java.util.concurrent.TimeUnit;12import java.util.HashMap;13import java.util.Map;14public class 3 {15 public static void main(String[] args) throws MalformedURLException {16 String seleniumIp = Environment.getSeleniumIp("DEV");17 ChromeOptions options = new ChromeOptions();18 options.addArguments("start-maximized");19 options.addArguments("disable-infobars");20 options.addArguments("--disable-extensions");21 options.addArguments("--disable-notifications");22 DesiredCapabilities capabilities = DesiredCapabilities.chrome();23 capabilities.setCapability(ChromeOptions.CAPABILITY, options);24 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);25 WebElement searchBox = driver.findElement(By.name("q"));26 searchBox.sendKeys("selenium webdriver");27 WebElement searchButton = driver.findElement(By.name("btnK"));28 searchButton.click();29 try {30 Thread.sleep(5000);31 }32 catch (InterruptedException e) {33 e.printStackTrace();34 }35 driver.quit();36 }37}

Full Screen

Full Screen

getSeleniumIp

Using AI Code Generation

copy

Full Screen

1package org.cerberus.crud.testdata;2import org.cerberus.crud.entity.Environment;3import org.cerberus.crud.factory.IFactoryEnvironment;4import org.cerberus.crud.service.IEnvironmentService;5import org.cerberus.engine.entity.MessageEvent;6import org.cerberus.engine.entity.MessageGeneral;7import org.cerberus.engine.execution.IRecorderService;8import org.cerberus.engine.execution.impl.RecorderService;9import org.cerberus.engine.queuemanagement.IExecutionThreadPoolService;10import org.cerberus.engine.queuemanagement.IExecutionThreadPoolServiceFactory;11import org.cerberus.engine.queuemanagement.impl.ExecutionThreadPoolServiceFactory;12import org.cerberus.exception.CerberusException;13import org.cerberus.service.engine.IParameterService;14import org.cerberus.service.engine.IRecorderService;15import org.cerberus.service.engine.IVariableService;16import org.cerberus.service.engine.impl.ParameterService;17import org.cerberus.service.engine.impl.RecorderService;18import org.cerberus.service.engine.impl.VariableService;19import org.cerberus.util.answer.AnswerItem;20import org.openqa.selenium.WebDriver;21public class Test {22 private IParameterService parameterService;23 private IVariableService variableService;24 private IRecorderService recorderService;25 private IEnvironmentService environmentService;26 private IFactoryEnvironment factoryEnvironment;27 public Test() {28 parameterService = new ParameterService();29 variableService = new VariableService();30 recorderService = new RecorderService();31 environmentService = new IEnvironmentService() {32 public void update(Environment object) {33 }34 public void create(Environment object) {35 }36 public void delete(Environment object) {37 }38 public AnswerItem readByKey(String system, String environment) {

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful