Example usage for org.openqa.selenium.remote RemoteWebDriver getSessionId

List of usage examples for org.openqa.selenium.remote RemoteWebDriver getSessionId

Introduction

In this page you can find the example usage for org.openqa.selenium.remote RemoteWebDriver getSessionId.

Prototype

public SessionId getSessionId() 

Source Link

Usage

From source file:com.epam.jdi.uitests.mobile.appium.driver.SauceLabRunner.java

License:Open Source License

public static void setSauceSessionID(RemoteWebDriver remoteDriver) {
    sessionId = remoteDriver.getSessionId().toString();
}

From source file:com.jhyhh.appium.AndroidDriverWait.java

License:Apache License

@Override
protected RuntimeException timeoutException(String message, Throwable lastException) {
    TimeoutException ex = new TimeoutException(message, lastException);
    ex.addInfo(WebDriverException.DRIVER_INFO, driver.getClass().getName());
    if (driver instanceof RemoteWebDriver) {
        RemoteWebDriver remote = (RemoteWebDriver) driver;
        if (remote.getSessionId() != null) {
            ex.addInfo(WebDriverException.SESSION_ID, remote.getSessionId().toString());
        }/*from   w w  w .  j a v a 2s  . c  o m*/
        if (remote.getCapabilities() != null) {
            ex.addInfo("Capabilities", remote.getCapabilities().toString());
        }
    }
    throw ex;
}

From source file:com.seleniumtests.connectors.selenium.SeleniumGridConnector.java

License:Apache License

public void runTest(RemoteWebDriver driver) {

    // logging node ip address:
    try {// ww w .j a  v  a 2s . c  om
        JSONObject object = Unirest
                .get(String.format("http://%s:%d/grid/api/testsession/", hubUrl.getHost(), hubUrl.getPort()))
                .queryString("session", driver.getSessionId().toString()).asJson().getBody().getObject();

        nodeUrl = (String) object.get("proxyId");
        String node = nodeUrl.split("//")[1].split(":")[0];
        String browserName = driver.getCapabilities().getBrowserName();
        String version = driver.getCapabilities().getVersion();

        // setting sessionId ensures that this connector is the active one
        sessionId = driver.getSessionId();
        logger.info("WebDriver is running on node " + node + ", " + browserName + " " + version + ", session "
                + sessionId);

    } catch (Exception ex) {
        logger.error(ex);
    }
}

From source file:com.timeinc.seleniumite.environment.LoggingRemoteWebDriverFactory.java

License:Open Source License

@Override
public RemoteWebDriver make(HashMap<String, String> hashMap) throws Exception {
    RemoteWebDriver rval = wrapped.make(hashMap);
    SessionId sessionId = rval.getSessionId();
    SessionRegistry.INSTANCE.store(scriptName, hashMap, sessionId);

    LOG.info("Create driver : {} : {} : {}", scriptName, hashMap, sessionId);
    return rval;/*from w w  w .  j av  a2  s  .com*/
}

From source file:com.vaadin.tests.elements.AbstractTB3Test.java

License:Apache License

protected String getRemoteControlName() {
    try {/*from  w  w  w.  j  a  v  a2 s .  c om*/
        RemoteWebDriver d = getRemoteDriver();
        if (d == null) {
            return null;
        }
        HttpCommandExecutor ce = (HttpCommandExecutor) d.getCommandExecutor();
        String hostName = ce.getAddressOfRemoteServer().getHost();
        int port = ce.getAddressOfRemoteServer().getPort();
        HttpHost host = new HttpHost(hostName, port);
        DefaultHttpClient client = new DefaultHttpClient();
        URL sessionURL = new URL(
                "http://" + hostName + ":" + port + "/grid/api/testsession?session=" + d.getSessionId());
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
                sessionURL.toExternalForm());
        HttpResponse response = client.execute(host, r);
        JsonObject object = extractObject(response);
        URL myURL = new URL(object.get("proxyId").getAsString());
        if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
            return myURL.getHost();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:galen.api.server.GalenCommandExecutor.java

License:Apache License

/**
 * Packages a successful session setup response which can be sent across the Thrift interface.
 */// w  w  w  .j  a v a  2 s .  co  m
private Response createSessionInitSuccessResponse(WebDriver driver) {
    Response response = new Response();
    response.setStatus(SUCCESS);
    RemoteWebDriver remoteDriver = (RemoteWebDriver) driver;
    ThriftValueWrapper wrappedValue = new ThriftValueWrapper(remoteDriver.getCapabilities().asMap());
    response.setResponse_value(wrappedValue.getValue());
    response.setContained_values(wrappedValue.getContainedValues());
    response.setSession_id(remoteDriver.getSessionId().toString());
    response.setState(new ErrorCodes().toState(SUCCESS));
    return response;
}

From source file:io.selendroid.server.model.SelendroidStandaloneDriver.java

License:Apache License

public String createNewTestSession(JSONObject caps, Integer retries) throws AndroidSdkException, JSONException {
    SelendroidCapabilities desiredCapabilities = null;

    // Convert the JSON capabilities to SelendroidCapabilities
    try {//from  w  w  w . j  a  v  a 2 s. co  m
        desiredCapabilities = new SelendroidCapabilities(caps);
    } catch (JSONException e) {
        throw new SelendroidException("Desired capabilities cannot be parsed.");
    }

    // Find the App being requested for use
    AndroidApp app = appsStore.get(desiredCapabilities.getAut());
    if (app == null) {
        throw new SessionNotCreatedException(
                "The requested application under test is not configured in selendroid server.");
    }
    // adjust app based on capabilities (some parameters are session specific)
    app = augmentApp(app, desiredCapabilities);

    // Find a device to match the capabilities
    AndroidDevice device = null;
    try {
        device = getAndroidDevice(desiredCapabilities);
    } catch (AndroidDeviceException e) {
        SessionNotCreatedException error = new SessionNotCreatedException(
                "Error occured while finding android device: " + e.getMessage());
        e.printStackTrace();
        log.severe(error.getMessage());
        throw error;
    }

    // If we are using an emulator need to start it up
    if (device instanceof AndroidEmulator) {
        AndroidEmulator emulator = (AndroidEmulator) device;
        try {
            if (emulator.isEmulatorStarted()) {
                emulator.unlockEmulatorScreen();
            } else {
                Map<String, Object> config = new HashMap<String, Object>();
                if (serverConfiguration.getEmulatorOptions() != null) {
                    config.put(AndroidEmulator.EMULATOR_OPTIONS, serverConfiguration.getEmulatorOptions());
                }
                config.put(AndroidEmulator.TIMEOUT_OPTION, serverConfiguration.getTimeoutEmulatorStart());
                if (desiredCapabilities.asMap().containsKey(SelendroidCapabilities.DISPLAY)) {
                    Object d = desiredCapabilities.getCapability(SelendroidCapabilities.DISPLAY);
                    config.put(AndroidEmulator.DISPLAY_OPTION, String.valueOf(d));
                }

                Locale locale = parseLocale(desiredCapabilities);
                emulator.start(locale, deviceStore.nextEmulatorPort(), config);
            }
        } catch (AndroidDeviceException e) {
            deviceStore.release(device, app);
            if (retries > 0) {
                return createNewTestSession(caps, retries - 1);
            }
            throw new SessionNotCreatedException(
                    "Error occured while interacting with the emulator: " + emulator + ": " + e.getMessage());
        }
        emulator.setIDevice(deviceManager.getVirtualDevice(emulator.getAvdName()));
    }
    boolean appInstalledOnDevice = device.isInstalled(app);
    if (!appInstalledOnDevice || serverConfiguration.isForceReinstall()) {
        device.install(app);
    } else {
        log.info("the app under test is already installed.");
    }

    int port = getNextSelendroidServerPort();
    Boolean selendroidInstalledSuccessfully = device.isInstalled("io.selendroid." + app.getBasePackage());
    if (!selendroidInstalledSuccessfully || serverConfiguration.isForceReinstall()) {
        AndroidApp selendroidServer = createSelendroidServerApk(app);

        selendroidInstalledSuccessfully = device.install(selendroidServer);
        if (!selendroidInstalledSuccessfully) {
            if (!device.install(selendroidServer)) {
                deviceStore.release(device, app);

                if (retries > 0) {
                    return createNewTestSession(caps, retries - 1);
                }
            }
        }
    } else {
        log.info(
                "selendroid-server will not be created and installed because it already exists for the app under test.");
    }

    // Run any adb commands requested in the capabilities
    List<String> adbCommands = new ArrayList<String>();
    adbCommands.add("shell setprop log.tag.SELENDROID " + serverConfiguration.getLogLevel().name());
    adbCommands.addAll(desiredCapabilities.getPreSessionAdbCommands());

    for (String adbCommandParameter : adbCommands) {
        device.runAdbCommand(adbCommandParameter);
    }

    // It's GO TIME!
    // start the selendroid server on the device and make sure it's up
    try {
        device.startSelendroid(app, port);
    } catch (AndroidSdkException e) {
        log.info("error while starting selendroid: " + e.getMessage());

        deviceStore.release(device, app);
        if (retries > 0) {
            return createNewTestSession(caps, retries - 1);
        }
        throw new SessionNotCreatedException(
                "Error occurred while starting instrumentation: " + e.getMessage());
    }
    long start = System.currentTimeMillis();
    long startTimeOut = 20000;
    long timemoutEnd = start + startTimeOut;
    while (device.isSelendroidRunning() == false) {
        if (timemoutEnd >= System.currentTimeMillis()) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
        } else {
            throw new SelendroidException(
                    "Selendroid server on the device didn't came up after " + startTimeOut / 1000 + "sec:");
        }
    }

    // arbitrary sleeps? yay...
    // looks like after the server starts responding
    // we need to give it a moment before starting a session?
    try {
        Thread.sleep(500);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    // create the new session on the device server
    RemoteWebDriver driver;
    try {
        driver = new RemoteWebDriver(new URL("http://localhost:" + port + "/wd/hub"), desiredCapabilities);
    } catch (Exception e) {
        e.printStackTrace();
        deviceStore.release(device, app);
        throw new SessionNotCreatedException("Error occurred while creating session on Android device", e);
    }
    String sessionId = driver.getSessionId().toString();
    SelendroidCapabilities requiredCapabilities = new SelendroidCapabilities(driver.getCapabilities().asMap());
    ActiveSession session = new ActiveSession(sessionId, requiredCapabilities, app, device, port, this);

    this.sessions.put(sessionId, session);

    // We are requesting an "AndroidDriver" so automatically switch to the webview
    if (BrowserType.ANDROID.equals(desiredCapabilities.getAut())) {
        // arbitrarily high wait time, will this cover our slowest possible device/emulator?
        WebDriverWait wait = new WebDriverWait(driver, 60);
        // wait for the WebView to appear
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("android.webkit.WebView")));
        driver.switchTo().window("WEBVIEW");
        // the 'android-driver' webview has an h1 with id 'AndroidDriver' embedded in it
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("AndroidDriver")));
    }

    return sessionId;
}

From source file:io.selendroid.standalone.server.model.SelendroidStandaloneDriver.java

License:Apache License

public String createNewTestSession(JSONObject caps, Integer retries) {
    AndroidDevice device = null;//  w  w  w  .j av a 2  s . c o  m
    AndroidApp app = null;
    Exception lastException = null;
    while (retries >= 0) {
        try {
            SelendroidCapabilities desiredCapabilities = getSelendroidCapabilities(caps);
            String desiredAut = desiredCapabilities.getDefaultApp(appsStore.keySet());
            app = getAndroidApp(desiredCapabilities, desiredAut);
            log.info("'" + desiredAut + "' will be used as app under test.");
            device = deviceStore.findAndroidDevice(desiredCapabilities);

            // If we are using an emulator need to start it up
            if (device instanceof AndroidEmulator) {
                startAndroidEmulator(desiredCapabilities, (AndroidEmulator) device);
            }

            boolean appInstalledOnDevice = device.isInstalled(app) || app instanceof InstalledAndroidApp;
            if (!appInstalledOnDevice || serverConfiguration.isForceReinstall()) {
                device.install(app);
            } else {
                log.info("the app under test is already installed.");
            }

            if (!serverConfiguration.isNoClearData()) {
                device.clearUserData(app);
            }

            int port = getNextSelendroidServerPort();
            boolean serverInstalled = device.isInstalled("io.selendroid." + app.getBasePackage());
            if (!serverInstalled || serverConfiguration.isForceReinstall()) {
                try {
                    device.install(createSelendroidServerApk(app));
                } catch (AndroidSdkException e) {
                    throw new SessionNotCreatedException("Could not install selendroid-server on the device",
                            e);
                }
            } else {
                log.info(
                        "Not creating and installing selendroid-server because it is already installed for this app under test.");
            }

            // Run any adb commands requested in the capabilities
            List<String> preSessionAdbCommands = desiredCapabilities.getPreSessionAdbCommands();
            runPreSessionCommands(device, preSessionAdbCommands);

            // Push extension dex to device if specified
            String extensionFile = desiredCapabilities.getSelendroidExtensions();
            pushExtensionsToDevice(device, extensionFile);

            // Configure logging on the device
            device.setLoggingEnabled(serverConfiguration.isDeviceLog());

            // It's GO TIME!
            // start the selendroid server on the device and make sure it's up
            eventListener.onBeforeDeviceServerStart();
            device.startSelendroid(app, port, desiredCapabilities);
            waitForServerStart(device);
            eventListener.onAfterDeviceServerStart();

            // arbitrary sleeps? yay...
            // looks like after the server starts responding
            // we need to give it a moment before starting a session?
            try {
                Thread.sleep(500);
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
            }

            // create the new session on the device server
            RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:" + port + "/wd/hub"),
                    desiredCapabilities);
            String sessionId = driver.getSessionId().toString();
            SelendroidCapabilities requiredCapabilities = new SelendroidCapabilities(
                    driver.getCapabilities().asMap());
            ActiveSession session = new ActiveSession(sessionId, requiredCapabilities, app, device, port, this);

            this.sessions.put(sessionId, session);

            // We are requesting an "AndroidDriver" so automatically switch to the webview
            if (BrowserType.ANDROID.equals(desiredCapabilities.getAut())) {
                switchToWebView(driver);
            }

            return sessionId;
        } catch (Exception e) {
            lastException = e;
            log.log(Level.SEVERE, "Error occurred while starting Selendroid session", e);
            retries--;

            // Return device to store
            if (device != null) {
                deviceStore.release(device, app);
                device = null;
            }
        }
    }

    if (lastException instanceof RuntimeException) {
        // Don't wrap the exception
        throw (RuntimeException) lastException;
    } else {
        throw new SessionNotCreatedException("Error starting Selendroid session", lastException);
    }
}

From source file:org.jboss.arquillian.ajocado2.reusable.TestReusingBrowserSession.java

License:Apache License

@Test
public void whenBrowserSessionIsCreatedThenCouldBeReused() throws UnableReuseSessionException {

    RemoteWebDriver driver = new RemoteWebDriver(HUB_URL, DesiredCapabilities.firefox());
    driver.navigate().to(SERVER_URL.toString());
    Capabilities reusedCapabilities = serializeDeserialize(driver.getCapabilities());
    SessionId reusedSessionId = new SessionId(serializeDeserialize(driver.getSessionId().toString()));

    ReusableRemoteWebDriver reusedDriver = new ReusableRemoteWebDriver(HUB_URL, reusedCapabilities,
            reusedSessionId);/*from w w w.java2 s  . co  m*/
    reusedDriver.navigate().to(HUB_URL.toString());
    reusedDriver.quit();
}

From source file:org.jboss.arquillian.ajocado2.reusable.TestReusingBrowserSession.java

License:Apache License

@Test
public void whenBrowserSessionIsCreatedAndQuitAndTriedToReuseThenItShouldThrowException() {

    RemoteWebDriver driver = new RemoteWebDriver(HUB_URL, DesiredCapabilities.firefox());
    driver.navigate().to(SERVER_URL.toString());
    Capabilities reusedCapabilities = serializeDeserialize(driver.getCapabilities());
    SessionId reusedSessionId = new SessionId(serializeDeserialize(driver.getSessionId().toString()));
    driver.quit();//from  w  ww .  j av  a 2 s.  com

    try {
        new ReusableRemoteWebDriver(HUB_URL, reusedCapabilities, reusedSessionId);
        fail("Original driver had quited before, so session should not be reusable");
    } catch (UnableReuseSessionException e) {
        // exception should be thrown
    }
}