Example usage for org.openqa.selenium.remote DriverCommand NEW_SESSION

List of usage examples for org.openqa.selenium.remote DriverCommand NEW_SESSION

Introduction

In this page you can find the example usage for org.openqa.selenium.remote DriverCommand NEW_SESSION.

Prototype

String NEW_SESSION

To view the source code for org.openqa.selenium.remote DriverCommand NEW_SESSION.

Click Source Link

Usage

From source file:com.mengge.remote.AppiumCommandExecutor.java

License:Apache License

@Override
public Response execute(Command command) throws IOException, WebDriverException {
    if (DriverCommand.NEW_SESSION.equals(command.getName()) && service != null) {
        service.start();/* w ww.j a  va 2  s  . c o  m*/
    }

    try {
        return super.execute(command);
    } catch (Throwable t) {
        Throwable rootCause = Throwables.getRootCause(t);
        if (rootCause instanceof ConnectException && rootCause.getMessage().contains("Connection refused")
                && service != null) {
            if (service.isRunning()) {
                throw new WebDriverException("The session is closed!", t);
            }

            if (!service.isRunning()) {
                throw new WebDriverException("The appium server has accidentally died!", t);
            }
        }
        Throwables.propagateIfPossible(t);
        throw new WebDriverException(t);
    } finally {
        if (DriverCommand.QUIT.equals(command.getName()) && service != null) {
            service.stop();
        }
    }
}

From source file:com.seleniumtests.ut.uipage.htmlelements.TestHtmlElement.java

License:Apache License

@BeforeMethod(groups = { "ut" })
private void init() throws WebDriverException, IOException {
    // mimic sub elements of the HtmlElement
    List<WebElement> subElList = new ArrayList<WebElement>();
    subElList.add(subElement1);/*from w w  w.ja v  a2  s .  c o  m*/
    subElList.add(subElement2);

    // list of elements correspond
    List<WebElement> elList = new ArrayList<WebElement>();
    elList.add(element);

    // add DriverExceptionListener to reproduce driver behavior
    eventDriver = spy(new CustomEventFiringWebDriver(driver).register(new DriverExceptionListener()));

    PowerMockito.mockStatic(WebUIDriver.class);
    when(WebUIDriver.getWebDriver()).thenReturn(eventDriver);
    when(driver.findElement(By.id("el"))).thenReturn(element);
    when(driver.findElements(By.name("subEl"))).thenReturn(subElList);
    when(driver.findElement(By.name("subEl"))).thenReturn(subElement1);
    when(driver.findElements(By.id("el"))).thenReturn(elList);
    when(driver.getKeyboard()).thenReturn(keyboard);
    when(driver.getMouse()).thenReturn(mouse);
    when(driver.switchTo()).thenReturn(locator);
    when(driver.executeScript(anyString())).thenReturn(Arrays.asList(100, 100));

    when(element.findElement(By.name("subEl"))).thenReturn(subElement1);
    when(element.findElements(By.name("subEl"))).thenReturn(subElList);
    when(element.getAttribute(anyString())).thenReturn("attribute");
    when(element.getSize()).thenReturn(new Dimension(10, 10));
    when(element.getLocation()).thenReturn(new Point(5, 5));
    when(element.getTagName()).thenReturn("h1");
    when(element.getText()).thenReturn("text");
    when(element.isDisplayed()).thenReturn(true);
    when(element.isEnabled()).thenReturn(true);

    when(subElement1.isDisplayed()).thenReturn(true);
    when(subElement2.isDisplayed()).thenReturn(true);
    when(subElement1.getLocation()).thenReturn(new Point(5, 5));
    when(subElement2.getLocation()).thenReturn(new Point(5, 5));

    when(mobileElement.getCenter()).thenReturn(new Point(2, 2));
    when(mobileElement.getLocation()).thenReturn(new Point(1, 1));
    when(mobileElement.isDisplayed()).thenReturn(true);
    when(mobileElement.getId()).thenReturn("12");

    // init for mobile tests
    AppiumCommandExecutor ce = Mockito.mock(AppiumCommandExecutor.class);
    Response response = new Response(new SessionId("1"));
    response.setValue(new HashMap<String, Object>());
    Response findResponse = new Response(new SessionId("1"));
    findResponse.setValue(mobileElement);

    when(ce.execute(any())).thenReturn(response, response, response, findResponse);
    doReturn(response).when(ce)
            .execute(argThat(command -> DriverCommand.NEW_SESSION.equals(command.getName())));
    doReturn(response).when(ce)
            .execute(argThat(command -> DriverCommand.FIND_ELEMENT.equals(command.getName())));
    doReturn(response).when(ce).execute(argThat(command -> "getSession".equals(command.getName())));

    // newSession, getSession, getSession, findElement

    mobileDriver = Mockito.spy(new AppiumDriver<>(ce, new DesiredCapabilities()));

    SeleniumTestsContextManager.getThreadContext().setTestType(TestType.WEB);
    SeleniumTestsContextManager.getThreadContext().setBrowser("htmlunit");
}

From source file:com.smash.revolance.ui.materials.mock.webdriver.browser.MockedBrowserController.java

License:Open Source License

@Override
public synchronized void notify(JSonWireEvent event) {
    String name = (String) event.getProp("command.name");
    String path = (String) event.getProp("command.path");
    String elementId = (String) event.getProp("command.elementId");
    String htmlAttribute = (String) event.getProp("command.elementHtmlAttribute");
    String cssAttribute = (String) event.getProp("command.elementCssAttribute");

    System.out.println("Receiving command: " + name + " with path: " + path);

    Map<String, Object> commandPayload = (Map<String, Object>) event.getProp("command.payload");

    // Just the value part in the payload
    Map<String, Object> resultPayload = new HashMap<String, Object>();

    if (isCommand(event, DriverCommand.NEW_SESSION)) {
        browser = new MockedBrowser();

        resultPayload.put("browserName", this.getClass().getSimpleName());
        resultPayload.put("browserPlatform", OS.isFamilyUnix() ? "LINUX" : "WINDOWS");
        resultPayload.put("browserVersion", "0.0.1-SNAPSHOT");
    }/*from  ww w  .  j a v  a  2  s .c o m*/
    if (isCommand(event, DriverCommand.SET_WINDOW_SIZE)) {
        browser.setSize((Integer) commandPayload.get("width"), (Integer) commandPayload.get("height"));
    }
    if (isCommand(event, DriverCommand.GET_WINDOW_SIZE)) {
        Dimension dim = browser.getDimension();
        resultPayload.put("width", dim.getWidth());
        resultPayload.put("height", dim.getHeight());
    }
    if (isCommand(event, DriverCommand.SET_WINDOW_POSITION)) {
        browser.setLocation((Integer) commandPayload.get("x"), (Integer) commandPayload.get("y"));
    }
    if (isCommand(event, DriverCommand.GET_WINDOW_POSITION)) {
        Point location = browser.getLocation();
        resultPayload.put("x", location.getX());
        resultPayload.put("y", location.getY());
    }
    if (isCommand(event, DriverCommand.GET_CURRENT_URL)) {
        resultPayload.put("url", browser.getUrl());
    }
    if (isCommand(event, DriverCommand.GET)) {
        try {
            browser.goToUrl((String) commandPayload.get("url"));
        } catch (Exception e) {
            System.err.println(e);
        }
    }
    if (isCommand(event, DriverCommand.EXECUTE_SCRIPT)) {
        resultPayload.put("value", browser.executeJavaScript((String) commandPayload.get("script"),
                (Object[]) commandPayload.get("args")));
    }
    if (isCommand(event, DriverCommand.GET_ALERT_TEXT)) {
        resultPayload.put("alertStatusCode", ErrorCodes.NO_ALERT_PRESENT);
        resultPayload.put("alertMessage", "No alert is present");
    }
    if (isCommand(event, DriverCommand.GET_TITLE)) {
        resultPayload.put("title", browser.getTitle());
    }
    if (isCommand(event, DriverCommand.SCREENSHOT)) {
        resultPayload.put("screenshot", browser.takeScreenshot());
    }
    if (isCommand(event, DriverCommand.FIND_ELEMENTS)) {
        List<String> elements = browser.findElements((String) commandPayload.get("value"));
        resultPayload.put("elementList", buildElementList(elements));
    }
    if (isCommand(event, DriverCommand.GET_ELEMENT_LOCATION)) {
        Point location = browser.getElementLocation(elementId);

        resultPayload.put("elementX", String.valueOf(location.getX()));
        resultPayload.put("elementY", String.valueOf(location.getY()));
    }
    if (isCommand(event, DriverCommand.GET_ELEMENT_SIZE)) {
        Dimension dim = browser.getElementSize(elementId);

        resultPayload.put("elementW", String.valueOf(dim.getWidth()));
        resultPayload.put("elementH", String.valueOf(dim.getHeight()));
    }
    if (isCommand(event, DriverCommand.GET_ELEMENT_TAG_NAME)) {
        resultPayload.put("elementTagName", browser.getElementTag(elementId));
    }
    if (isCommand(event, DriverCommand.GET_ELEMENT_TEXT)) {
        resultPayload.put("elementText", browser.getElementText(elementId));
    }
    if (isCommand(event, DriverCommand.GET_ELEMENT_ATTRIBUTE)) {
        resultPayload.put("elementHtmlAttributeValue",
                browser.getElementHtmlAttribute(elementId, htmlAttribute));
    }
    if (isCommand(event, DriverCommand.IS_ELEMENT_DISPLAYED)) {
        resultPayload.put("isElementDisplayed", browser.isElementDisplayed(elementId));
    }
    if (isCommand(event, DriverCommand.GET_ELEMENT_VALUE_OF_CSS_PROPERTY)) {
        resultPayload.put("elementCssAttributeValue", browser.getElementCssAttribute(elementId, cssAttribute));
    }
    event.setProp("command.value", resultPayload);
    notifyAll();
}

From source file:com.smash.revolance.ui.materials.mock.webdriver.handler.JSonWireController.java

License:Open Source License

@POST
@Path("/session")
@Consumes(MediaType.APPLICATION_JSON)/*from  w  ww .j  av a2 s  . c  o m*/
@Produces(MediaType.APPLICATION_JSON)
public Response createSession() {
    Command cmd = new Command(UUID.randomUUID().toString(), DriverCommand.NEW_SESSION, "POST");
    CommandResult cmdResult = new CommandExecutor(cmd, getPath()).execute();
    return new CommandResponse(cmdResult).buildResponse();
}

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

License:Apache License

/**
 * Executes the command received over the Thrift interface inside an instance of RemoteWebDriver.
 * @param sessionId WebDriver SessionId.
 * @param commandName Command name./*  w  ww .ja  va2s  . co m*/
 * @param params Command params.
 * @return an instance of {@link org.openqa.selenium.remote.Response}
 * @throws TException
 */
@Override
public Response execute(String sessionId, String commandName, String params) throws TException {
    Map<String, Object> paramsAsMap = fromJsonToStringObjectMap(params);
    if (commandName.equals(DriverCommand.NEW_SESSION)) {
        try {
            log.info("Setting up new WebDriver session");
            HashMap<String, Object> hashMap = extractDesiredCapabilities(paramsAsMap);
            WebDriver driver = new RemoteWebDriver(new URL(remoteServerAddress),
                    new DesiredCapabilities(hashMap));
            DriversPool.get().set(driver);
            return createSessionInitSuccessResponse(driver);
        } catch (MalformedURLException e) {
            log.error("Provided URL is malformed " + remoteServerAddress);
            return createSessionInitFailureResponse("Provided URL is malformed " + remoteServerAddress);
        } catch (UnreachableBrowserException e) {
            log.error("Could not reach browser at URL " + remoteServerAddress
                    + " check remote server is running.");
            return createSessionInitFailureResponse("Could not reach browser at URL " + remoteServerAddress
                    + " check remote server is running.");
        } catch (WebDriverException e) {
            throw new RemoteWebDriverException(e.getMessage());
        }
    }
    Command driverCommand = new Command(new SessionId(sessionId), handleCommandNameExceptions(commandName),
            paramsAsMap);
    try {
        log.info(format("Executing command %s for sessionId %s", commandName, sessionId));
        WebDriver driver = DriversPool.get().getBySessionId(sessionId);
        org.openqa.selenium.remote.Response response = null;
        if (driver instanceof RemoteWebDriver) {
            response = ((RemoteWebDriver) driver).getCommandExecutor().execute(driverCommand);
        }
        if (response == null) {
            return null;
        } else {
            if (commandName.equals(DriverCommand.QUIT)) {
                DriversPool.get().removeDriverBySessionId(sessionId);
            }
            ThriftValueWrapper valueWrapper = new ThriftValueWrapper(response.getValue());
            return new Response(valueWrapper.getValue(), valueWrapper.getContainedValues(),
                    response.getSessionId(), response.getStatus(), response.getState());
        }
    } catch (IOException ioe) {
        log.error(format("IOException while executing command %s: %s", commandName, ioe.toString()));
    } catch (WebDriverException wex) {
        log.error(format("WebDriverException while executing command %s: + %s", commandName, wex.toString()));
        throw new RemoteWebDriverException(wex.getMessage());
    }
    return null;
}

From source file:io.appium.java_client.remote.AppiumCommandExecutor.java

License:Apache License

@Override
public Response execute(Command command) throws IOException, WebDriverException {
    if (DriverCommand.NEW_SESSION.equals(command.getName()) && service != null) {
        service.start();/*from  w  w w .j a  va 2  s .c  o m*/
    }

    try {
        return super.execute(command);
    } catch (Throwable t) {
        Throwable rootCause = Throwables.getRootCause(t);
        if (rootCause instanceof ConnectException && rootCause.getMessage().contains("Connection refused")
                && service != null) {
            if (service.isRunning())
                throw new WebDriverException("The session is closed!", t);

            if (!service.isRunning())
                throw new WebDriverException("The appium server has accidentally died!", t);
        }
        Throwables.propagateIfPossible(t);
        throw new WebDriverException(t);
    } finally {
        if (DriverCommand.QUIT.equals(command.getName()) && service != null) {
            service.stop();
        }
    }
}