Example usage for org.openqa.selenium.remote Response setValue

List of usage examples for org.openqa.selenium.remote Response setValue

Introduction

In this page you can find the example usage for org.openqa.selenium.remote Response setValue.

Prototype

public void setValue(Object value) 

Source Link

Usage

From source file:com.jobaline.uiautomation.framework.selenium.phantomJsThreeHourTimeoutFix.HttpCommandExecutor.java

License:Apache License

private Response createResponse(HttpResponse httpResponse, HttpContext context,
        EntityWithEncoding entityWithEncoding) throws IOException {
    final Response response;

    Header header = httpResponse.getFirstHeader("Content-Type");

    if (header != null && header.getValue().startsWith("application/json")) {
        String responseAsText = entityWithEncoding.getContentString();

        try {//ww w .  j  a v a2 s.com
            response = new JsonToBeanConverter().convert(Response.class, responseAsText);
        } catch (ClassCastException e) {
            if (responseAsText != null && "".equals(responseAsText)) {
                // The remote server has died, but has already set some headers.
                // Normally this occurs when the final window of the firefox driver
                // is closed on OS X. Return null, as the return value _should_ be
                // being ignored. This is not an elegant solution.
                return null;
            }
            throw new WebDriverException("Cannot convert text to response: " + responseAsText, e);
        }
    } else {
        response = new Response();

        if (header != null && header.getValue().startsWith("image/png")) {
            response.setValue(entityWithEncoding.getContent());
        } else if (entityWithEncoding.hasEntityContent()) {
            response.setValue(entityWithEncoding.getContentString());
        }

        HttpHost finalHost = (HttpHost) context.getAttribute(HTTP_TARGET_HOST);
        String uri = finalHost.toURI();
        String sessionId = HttpSessionId.getSessionId(uri);
        if (sessionId != null) {
            response.setSessionId(sessionId);
        }

        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (!(statusCode > 199 && statusCode < 300)) {
            // 4xx represents an unknown command or a bad request.
            if (statusCode > 399 && statusCode < 500) {
                response.setStatus(ErrorCodes.UNKNOWN_COMMAND);
            } else if (statusCode > 499 && statusCode < 600) {
                // 5xx represents an internal server error. The response status should already be set, but
                // if not, set it to a general error code.
                if (response.getStatus() == ErrorCodes.SUCCESS) {
                    response.setStatus(ErrorCodes.UNHANDLED_ERROR);
                }
            } else {
                response.setStatus(ErrorCodes.UNHANDLED_ERROR);
            }
        }

        if (response.getValue() instanceof String) {
            // We normalise to \n because Java will translate this to \r\n
            // if this is suitable on our platform, and if we have \r\n, java will
            // turn this into \r\r\n, which would be Bad!
            response.setValue(((String) response.getValue()).replace("\r\n", "\n"));
        }
    }

    response.setState(errorCodes.toState(response.getStatus()));
    return response;
}

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  www .  j a  va 2s .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:io.appium.java_client.remote.AppiumProtocolHandShake.java

License:Apache License

private Optional<Result> createSession(HttpClient client, JsonObject params) throws IOException {
    // Create the http request and send it
    HttpRequest request = new HttpRequest(HttpMethod.POST, "/session");
    String content = params.toString();
    byte[] data = content.getBytes(UTF_8);

    request.setHeader(CONTENT_LENGTH, String.valueOf(data.length));
    request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
    request.setContent(data);/*from w  ww. j ava2  s. co  m*/
    HttpResponse response = client.execute(request, true);

    Map<?, ?> jsonBlob = new HashMap<>();
    String resultString = response.getContentString();
    try {
        jsonBlob = new JsonToBeanConverter().convert(Map.class, resultString);
    } catch (ClassCastException e) {
        return Optional.empty();
    } catch (JsonException e) {
        // Fine. Handle that below
    }

    // If the result looks positive, return the result.
    Object sessionId = jsonBlob.get("sessionId");
    Object value = jsonBlob.get("value");
    Object w3cError = jsonBlob.get("error");
    Object ossStatus = jsonBlob.get("status");
    Map<String, ?> capabilities = null;
    if (value != null && value instanceof Map) {
        capabilities = (Map<String, ?>) value;
    } else if (value != null && value instanceof Capabilities) {
        capabilities = ((Capabilities) capabilities).asMap();
    }

    if (response.getStatus() == HttpURLConnection.HTTP_OK && sessionId != null && capabilities != null) {
        Dialect dialect = ossStatus == null ? Dialect.W3C : Dialect.OSS;
        return Optional.of(new Result(dialect, String.valueOf(sessionId), capabilities));
    }

    // If the result was an error that we believe has to do with the remote end failing to start the
    // session, create an exception and throw it.
    Response tempResponse = null;
    if ("session not created".equals(w3cError)) {
        tempResponse = new Response(null);
        tempResponse.setStatus(SESSION_NOT_CREATED);
        tempResponse.setValue(jsonBlob);
    } else if (ossStatus instanceof Number && ((Number) ossStatus).intValue() == SESSION_NOT_CREATED) {
        tempResponse = new Response(null);
        tempResponse.setStatus(SESSION_NOT_CREATED);
        tempResponse.setValue(jsonBlob);
    }

    if (tempResponse != null) {
        new ErrorHandler().throwIfResponseFailed(tempResponse, 0);
    }

    // Otherwise, just return empty.
    return Optional.empty();
}

From source file:org.uiautomation.ios.server.command.BaseCommandHandler.java

License:Apache License

protected Response createResponse(Object value) {
    Response r = new Response();
    r.setSessionId(getSession().getSessionId());
    r.setStatus(0);/*from  ww  w.  ja  v  a 2s .  c o  m*/
    r.setValue(value);
    return r;
}

From source file:org.uiautomation.ios.server.command.UIAScriptHandler.java

License:Apache License

public Response handle() throws Exception {
    if (js == null) {
        throw new RuntimeException("need to specify the JS to run");
    }//from  www  . j  a v  a 2 s .c o  m
    UIAScriptRequest r = new UIAScriptRequest(js);
    communication().sendNextCommand(r);

    Response response;
    // Stop is a fire and forget response. It will kill the instruments script,
    // so the script cannot
    // send a response.
    if ("stop".equals(js)) {
        response = new Response();
        response.setSessionId(getRequest().getSession());
        response.setStatus(0);
        response.setValue("ok");
    } else {
        response = communication().waitForResponse().getResponse();
    }
    return response;
}

From source file:org.uiautomation.ios.server.command.uiautomation.FlickNHandler.java

License:Apache License

public Point getStartCoordinatesCentered(WebDriverLikeRequest request, String elementId)
        throws InterruptedException {
    String getElementJS = getElementTemplate.replace(":reference", elementId).replace(":sessionId",
            request.getSession());// www  .j  a  va2 s . co  m

    UIAScriptRequest r = new UIAScriptRequest(getElementJS);
    communication().sendNextCommand(r);
    Response response;
    if ("stop".equals(getElementJS)) {
        response = new Response();
        response.setSessionId(getRequest().getSession());
        response.setStatus(0);
        response.setValue("ok");
    } else {
        response = communication().waitForResponse().getResponse();
    }

    return CoordinateUtils.getCenterPointFromResponse(response);
}

From source file:org.uiautomation.ios.server.command.uiautomation.GetConfigurationNHandler.java

License:Apache License

@Override
public Response handle() throws Exception {
    String name = (String) getRequest().getVariableValue(":command");
    WebDriverLikeCommand command = WebDriverLikeCommand.valueOf(name);

    CommandConfiguration conf = getSession().configure(command);

    JSONObject res = new JSONObject();
    Map<String, Object> m = conf.getAll();
    for (String key : m.keySet()) {
        res.put(key, m.get(key));/*from  w  w w  .j  a v a2  s  .  co m*/
    }

    Response resp = new Response();
    resp.setSessionId(getSession().getSessionId());
    resp.setStatus(0);
    resp.setValue(res);
    return resp;
}

From source file:org.uiautomation.ios.server.command.uiautomation.GetCurrentContextNHandler.java

License:Apache License

@Override
public Response handle() throws Exception {
    WorkingMode mode = getSession().getWorkingMode();
    String value = mode.toString();
    if (mode == WorkingMode.Web) {
        value = WorkingMode.Web + "_" + getSession().getRemoteWebDriver().getWindowHandle();
    }/* ww w .  j  av  a 2 s  .  co m*/
    Response resp = new Response();
    resp.setSessionId(getSession().getSessionId());
    resp.setStatus(0);
    resp.setValue(value);
    return resp;
}

From source file:org.uiautomation.ios.server.command.uiautomation.GetSessionsNHandler.java

License:Apache License

@Override
public Response handle() throws Exception {
    JSONArray res = new JSONArray();

    List<ServerSideSession> sessions = getDriver().getSessions();

    for (ServerSideSession s : sessions) {
        JSONObject session = new JSONObject();
        session.put("id", s.getSessionId());

        IOSRunningApplication app = s.getApplication();
        IOSCapabilities cap = app.getCapabilities();
        session.put("capabilities", cap.getRawCapabilities());
        res.put(session);/*from w  w w  .  ja  va 2s . c  om*/
    }
    Response resp = new Response();
    resp.setSessionId("dummy one");
    resp.setStatus(0);
    resp.setValue(res.toString());
    return resp;
}

From source file:org.uiautomation.ios.server.command.uiautomation.GetWindowHandlesNHandler.java

License:Apache License

@Override
public Response handle() throws Exception {

    ServerSideSession sss = getDriver().getSession(getRequest().getSession());

    Set<String> handles = new HashSet<String>();
    handles.add(WorkingMode.Native.toString());

    if (sss.getNativeDriver().findElements(new TypeCriteria(UIAWebView.class)).size() > 0) {
        for (WebkitPage page : getSession().getRemoteWebDriver().getPages()) {
            handles.add(WorkingMode.Web + "_" + page.getPageId());
        }//from ww  w . ja  v a  2  s  .com
    }

    Response resp = new Response();
    resp.setSessionId(getSession().getSessionId());
    resp.setStatus(0);
    resp.setValue(handles);
    return resp;
}