Best Gridrouter code snippet using ru.qatools.gridrouter.RouteServlet.route
Source:RouteServlet.java
1package ru.qatools.gridrouter;2import com.fasterxml.jackson.core.JsonProcessingException;3import org.apache.commons.io.IOUtils;4import org.apache.http.HttpResponse;5import org.apache.http.client.config.RequestConfig;6import org.apache.http.client.methods.HttpPost;7import org.apache.http.entity.StringEntity;8import org.apache.http.impl.client.CloseableHttpClient;9import org.apache.http.impl.client.HttpClientBuilder;10import org.apache.http.impl.client.LaxRedirectStrategy;11import org.slf4j.Logger;12import org.slf4j.LoggerFactory;13import org.springframework.beans.factory.annotation.Autowired;14import org.springframework.beans.factory.annotation.Value;15import ru.qatools.gridrouter.caps.CapabilityProcessorFactory;16import ru.qatools.gridrouter.config.Host;17import ru.qatools.gridrouter.config.HostSelectionStrategy;18import ru.qatools.gridrouter.config.Region;19import ru.qatools.gridrouter.config.Version;20import ru.qatools.gridrouter.json.JsonCapabilities;21import ru.qatools.gridrouter.json.JsonMessage;22import ru.qatools.gridrouter.json.JsonMessageFactory;23import ru.qatools.gridrouter.sessions.AvailableBrowserCheckExeption;24import ru.qatools.gridrouter.sessions.AvailableBrowsersChecker;25import ru.qatools.gridrouter.sessions.StatsCounter;26import javax.servlet.ServletException;27import javax.servlet.annotation.HttpConstraint;28import javax.servlet.annotation.ServletSecurity;29import javax.servlet.annotation.WebServlet;30import javax.servlet.http.HttpServletRequest;31import javax.servlet.http.HttpServletResponse;32import java.io.IOException;33import java.io.OutputStream;34import java.time.Instant;35import java.util.ArrayList;36import java.util.List;37import java.util.concurrent.Callable;38import java.util.concurrent.Executors;39import java.util.concurrent.ScheduledExecutorService;40import java.util.concurrent.TimeUnit;41import java.util.concurrent.atomic.AtomicBoolean;42import java.util.concurrent.atomic.AtomicLong;43import static java.lang.String.format;44import static java.nio.charset.StandardCharsets.UTF_8;45import static java.util.stream.Collectors.toList;46import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;47import static javax.servlet.http.HttpServletResponse.SC_OK;48import static org.apache.http.HttpHeaders.ACCEPT;49import static org.apache.http.entity.ContentType.APPLICATION_JSON;50import static ru.qatools.gridrouter.RequestUtils.getRemoteHost;51/**52 * @author Alexander Andyashin aandryashin@yandex-team.ru53 * @author Dmitry Baev charlie@yandex-team.ru54 * @author Innokenty Shuvalov innokenty@yandex-team.ru55 * @author Artem Eroshenko eroshenkoam@yandex-team.ru56 */57@WebServlet(urlPatterns = {"/wd/hub/session"}, asyncSupported = true)58@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user"}))59public class RouteServlet extends SpringHttpServlet {60 private static final Logger LOGGER = LoggerFactory.getLogger(RouteServlet.class);61 private static final String ROUTE_TIMEOUT_CAPABILITY = "grid.router.route.timeout.seconds";62 private static final int MAX_ROUTE_TIMEOUT_SECONDS = 300;63 @Autowired64 private transient ConfigRepository config;65 @Autowired66 private transient HostSelectionStrategy hostSelectionStrategy;67 @Autowired68 private transient StatsCounter statsCounter;69 @Autowired70 private transient CapabilityProcessorFactory capabilityProcessorFactory;71 @Autowired72 private transient AvailableBrowsersChecker avblBrowsersChecker;73 @Value("${grid.router.route.timeout.seconds:120}")74 private int routeTimeout;75 private AtomicLong requestCounter = new AtomicLong();76 @Override77 protected void doPost(HttpServletRequest request, HttpServletResponse response)78 throws ServletException, IOException {79 ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);80 JsonMessage message = JsonMessageFactory.from(request.getInputStream());81 long requestId = requestCounter.getAndIncrement();82 int routeTimeout = getRouteTimeout(request.getRemoteUser(), message);83 AtomicBoolean terminated = new AtomicBoolean(false);84 executor.submit(getRouteCallable(request, message, response, requestId, routeTimeout, terminated));85 executor.shutdown();86 try {87 executor.awaitTermination(routeTimeout, TimeUnit.SECONDS);88 terminated.set(true);89 } catch (InterruptedException e) {90 executor.shutdownNow();91 }92 replyWithError("Timed out when searching for valid host", response);93 }94 private Callable<Object> getRouteCallable(HttpServletRequest request, JsonMessage message, HttpServletResponse response,95 long requestId, int routeTimeout, AtomicBoolean terminated) {96 return () -> {97 route(request, message, response, requestId, routeTimeout, terminated);98 return null;99 };100 }101 private int getRouteTimeout(String user, JsonMessage message) {102 JsonCapabilities caps = message.getDesiredCapabilities();103 try {104 if (caps.any().containsKey(ROUTE_TIMEOUT_CAPABILITY)) {105 Integer desiredRouteTimeout = Integer.valueOf(String.valueOf(caps.any().get(ROUTE_TIMEOUT_CAPABILITY)));106 routeTimeout = (desiredRouteTimeout < MAX_ROUTE_TIMEOUT_SECONDS) ?107 desiredRouteTimeout :108 MAX_ROUTE_TIMEOUT_SECONDS;109 LOGGER.warn("[{}] [INVALID_ROUTE_TIMEOUT] [{}]", user, desiredRouteTimeout);110 }111 } catch (NumberFormatException ignored) {112 }113 return routeTimeout;114 }115 private void route(HttpServletRequest request, JsonMessage message,116 HttpServletResponse response,117 long requestId, int routeTimeout, AtomicBoolean terminated) throws IOException {118 long initialSeconds = Instant.now().getEpochSecond();119 JsonCapabilities caps = message.getDesiredCapabilities();120 String user = request.getRemoteUser();121 String remoteHost = getRemoteHost(request);122 String browser = caps.describe();123 Version actualVersion = config.findVersion(user, caps);124 if (actualVersion == null) {125 LOGGER.warn("[{}] [UNSUPPORTED_BROWSER] [{}] [{}] [{}]", requestId, user, remoteHost, browser);126 replyWithError(format("Cannot find %s capabilities on any available node",127 caps.describe()), response);128 return;129 }130 caps.setVersion(actualVersion.getNumber());131 capabilityProcessorFactory.getProcessor(caps).process(caps);132 List<Region> allRegions = actualVersion.getRegions()133 .stream().map(Region::copy).collect(toList());134 List<Region> unvisitedRegions = new ArrayList<>(allRegions);135 int attempt = 0;136 JsonMessage hubMessage = null;137 try (CloseableHttpClient client = newHttpClient(routeTimeout * 1000)) {138 if (actualVersion.getPermittedCount() != null) {139 avblBrowsersChecker.ensureFreeBrowsersAvailable(user, remoteHost, browser, actualVersion);140 }141 while (!allRegions.isEmpty() && !terminated.get()) {142 attempt++;143 Region currentRegion = hostSelectionStrategy.selectRegion(allRegions, unvisitedRegions);144 Host host = hostSelectionStrategy.selectHost(currentRegion.getHosts());145 String route = host.getRoute();146 try {147 LOGGER.info("[{}] [SESSION_ATTEMPTED] [{}] [{}] [{}] [{}] [{}]", requestId, user, remoteHost, browser, route, attempt);148 String target = route + request.getRequestURI();149 HttpResponse hubResponse = client.execute(post(target, message));150 hubMessage = JsonMessageFactory.from(hubResponse.getEntity().getContent());151 if (hubResponse.getStatusLine().getStatusCode() == SC_OK) {152 String sessionId = hubMessage.getSessionId();153 hubMessage.setSessionId(host.getRouteId() + sessionId);154 replyWithOk(hubMessage, response);155 long createdDurationSeconds = Instant.now().getEpochSecond() - initialSeconds;156 LOGGER.info("[{}] [{}] [SESSION_CREATED] [{}] [{}] [{}] [{}] [{}] [{}]",157 requestId, createdDurationSeconds, user, remoteHost, browser, route, sessionId, attempt);158 statsCounter.startSession(hubMessage.getSessionId(), user, caps.getBrowserName(), actualVersion.getNumber(), route);159 return;160 }161 LOGGER.warn("[{}] [SESSION_FAILED] [{}] [{}] [{}] [{}] - {}",162 requestId, user, remoteHost, browser, route, hubMessage.getErrorMessage());163 } catch (JsonProcessingException exception) {164 LOGGER.error("[{}] [BAD_HUB_JSON] [{}] [{}] [{}] [{}] - {}", "",165 requestId, user, remoteHost, browser, route, exception.getMessage());166 } catch (IOException exception) {167 LOGGER.error("[{}] [HUB_COMMUNICATION_FAILURE] [{}] [{}] [{}] - {}",168 requestId, user, remoteHost, browser, route, exception.getMessage());169 }170 currentRegion.getHosts().remove(host);171 if (currentRegion.getHosts().isEmpty()) {172 allRegions.remove(currentRegion);173 }174 unvisitedRegions.remove(currentRegion);175 if (unvisitedRegions.isEmpty()) {176 unvisitedRegions = new ArrayList<>(allRegions);177 }178 }179 } catch (AvailableBrowserCheckExeption e) {180 LOGGER.error("[{}] [AVAILABLE_BROWSER_CHECK_ERROR] [{}] [{}] [{}] - {}",181 requestId, user, remoteHost, browser, e.getMessage());182 }...
route
Using AI Code Generation
1import ru.qatools.gridrouter.RouteServlet2import ru.qatools.gridrouter.config.Config3import ru.qatools.gridrouter.config.Grid4import ru.qatools.gridrouter.config.GridRouter5import ru.qatools.gridrouter.config.Host6import ru.qatools.gridrouter.config.Hosts7import ru.qatools.gridrouter.utils.HttpUtil8def gridRouter = Config.loadConfig()9def grid = gridRouter.grids.find { it.name == "grid1" }10def host = grid.hosts.find { it.name == "host1" }11def route = RouteServlet.route(gridRouter, grid, host)
route
Using AI Code Generation
1import java.io.IOException;2import java.io.InputStream;3import java.io.InputStreamReader;4import java.io.OutputStream;5import java.net.HttpURLConnection;6import java.net.URL;7import java.util.Arrays;8import java.util.HashMap;9import java.util.List;10import java.util.Map;11import org.apache.http.HttpEntity;12import org.apache.http.HttpResponse;13import org.apache.http.client.methods.HttpPost;14import org.apache.http.entity.StringEntity;15import org.apache.http.impl.client.DefaultHttpClient;16import org.apache.http.util.EntityUtils;17import org.junit.Assert;18import org.junit.Test;19import com.google.gson.Gson;20import com.google.gson.reflect.TypeToken;21public class TestRouteServlet {22 public void testRouteServlet() throws IOException {23 String host = "localhost";24 int port = 4444;25 String routeName = "test";26 String route = routeUrl + "/" + routeName;27 String routeServletUrl = routeUrl + "/route";28 Map<String, Object> routeData = new HashMap<String, Object>();29 routeData.put("name", routeName);30 routeData.put("hubUrl", hubUrl);31 routeData.put("routeUrl", routeUrl);32 routeData.put("route", route);33 routeData.put("priority", 1);34 Gson gson = new Gson();35 String routeDataJson = gson.toJson(routeData);36 System.out.println("routeDataJson: " + routeDataJson);37 URL url = new URL(routeServletUrl);38 HttpURLConnection conn = (HttpURLConnection) url.openConnection();39 conn.setRequestMethod("POST");40 conn.setRequestProperty("Accept", "application/json");41 conn.setRequestProperty("Content-Type", "application/json");42 conn.setDoOutput(true);
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!