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

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

Introduction

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

Prototype

public Response() 

Source Link

Usage

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

License:Apache License

public Response execute(Command command) throws IOException {
    HttpContext context = new BasicHttpContext();

    if (command.getSessionId() == null) {
        if (QUIT.equals(command.getName())) {
            return new Response();
        }//  w  w  w. j  a va 2s .  com
        if (!GET_ALL_SESSIONS.equals(command.getName()) && !NEW_SESSION.equals(command.getName())) {
            throw new SessionNotFoundException("Session ID is null. Using WebDriver after calling quit()?");
        }
    }

    CommandInfo info = nameToUrl.get(command.getName());
    try {
        HttpUriRequest httpMethod = info.getMethod(remoteServer, command);

        setAcceptHeader(httpMethod);

        if (httpMethod instanceof HttpPost) {
            String payload = new BeanToJsonConverter().convert(command.getParameters());
            ((HttpPost) httpMethod).setEntity(new StringEntity(payload, "utf-8"));
            httpMethod.addHeader("Content-Type", "application/json; charset=utf-8");
        }

        // Do not allow web proxy caches to cache responses to "get" commands
        if (httpMethod instanceof HttpGet) {
            httpMethod.addHeader("Cache-Control", "no-cache");
        }

        log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), true));
        HttpResponse response = fallBackExecute(context, httpMethod);
        log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), false));

        response = followRedirects(client, context, response, /* redirect count */0);

        final EntityWithEncoding entityWithEncoding = new EntityWithEncoding(response.getEntity());

        return createResponse(response, context, entityWithEncoding);
    } catch (UnsupportedCommandException e) {
        if (e.getMessage() == null || "".equals(e.getMessage())) {
            throw new UnsupportedOperationException(
                    "No information from server. Command name was: " + command.getName(), e.getCause());
        }
        throw e;
    }
}

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 a 2  s  . c  o m*/
            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.qmetry.qaf.automation.ui.webdriver.LiveIsExtendedWebDriver.java

License:Open Source License

@Override
protected Response execute(String driverCommand, Map<String, ?> parameters) {
    if (driverCommand.equalsIgnoreCase(DriverCommand.QUIT)) {
        return new Response();
    }//from  www .java2s  . c  o  m
    return super.execute(driverCommand, parameters);
}

From source file:org.aludratest.service.gui.web.selenium.selenium2.AludraSeleniumHttpCommandExecutor.java

License:Apache License

@Override
public Response execute(Command command) throws IOException {
    HttpContext context = new BasicHttpContext();

    if (command.getSessionId() == null) {
        if (QUIT.equals(command.getName())) {
            return new Response();
        }//from   w w w  . j  a v  a 2s  . com
        if (!GET_ALL_SESSIONS.equals(command.getName()) && !NEW_SESSION.equals(command.getName())) {
            throw new SessionNotFoundException("Session ID is null. Using WebDriver after calling quit()?");
        }
    }

    HttpRequest request = commandCodec.encode(command);

    String requestUrl = remoteServer.toExternalForm().replaceAll("/$", "") + request.getUri();

    HttpUriRequest httpMethod = createHttpUriRequest(request.getMethod(), requestUrl);
    for (String name : request.getHeaderNames()) {
        // Skip content length as it is implicitly set when the message entity is set below.
        if (!"Content-Length".equalsIgnoreCase(name)) {
            for (String value : request.getHeaders(name)) {
                httpMethod.addHeader(name, value);
            }
        }
    }

    if (httpMethod instanceof HttpPost) {
        ((HttpPost) httpMethod).setEntity(new ByteArrayEntity(request.getContent()));
    }

    if (requestTimeout > 0 && (httpMethod instanceof HttpRequestBase)) {
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(15000)
                .setConnectTimeout(15000).setSocketTimeout(requestTimeout).build();
        ((HttpRequestBase) httpMethod).setConfig(requestConfig);
    } else if (httpMethod instanceof HttpRequestBase) {
        // ensure Selenium Standard is set
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000)
                .setConnectTimeout(60000).setSocketTimeout(THREE_HOURS).build();
        ((HttpRequestBase) httpMethod).setConfig(requestConfig);
    }

    try {
        log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), true));
        HttpResponse response = fallBackExecute(context, httpMethod);
        log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), false));

        lastResponse = response;
        response = followRedirects(client, context, response, /* redirect count */0);
        lastResponse = response;

        return createResponse(response, context);
    } catch (UnsupportedCommandException e) {
        if (e.getMessage() == null || "".equals(e.getMessage())) {
            throw new UnsupportedOperationException(
                    "No information from server. Command name was: " + command.getName(), e.getCause());
        }
        throw e;
    } catch (SocketTimeoutException e) {
        LoggerFactory.getLogger(AludraSeleniumHttpCommandExecutor.class)
                .warn("Timeout in HTTP Command Executor. Timeout was "
                        + ((HttpRequestBase) httpMethod).getConfig().getSocketTimeout());
        throw e;
    }
}

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);//  w ww . j  a  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");
    }//w w  w. j a v a2s  .  co  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());/*from  ww  w.  j  ava  2 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 ww w . j  av  a 2 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();
    }//  w  w w .  j a  va2s  . c o 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);/*w w  w . j a  v  a  2  s. co  m*/
    }
    Response resp = new Response();
    resp.setSessionId("dummy one");
    resp.setStatus(0);
    resp.setValue(res.toString());
    return resp;
}