Best Gridrouter code snippet using ru.qatools.gridrouter.json.JsonMessageFactory
Source:RouteServlet.java
...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 }183 LOGGER.error("[{}] [SESSION_NOT_CREATED] [{}] [{}] [{}]", requestId, user, remoteHost, browser);184 if (hubMessage == null) {185 replyWithError("Cannot create session on any available node", response);186 } else {187 replyWithError(hubMessage, response);188 }189 }190 protected void replyWithOk(JsonMessage message, HttpServletResponse response) throws IOException {191 reply(SC_OK, message, response);192 }193 protected void replyWithError(String errorMessage, HttpServletResponse response) throws IOException {194 replyWithError(JsonMessageFactory.error(13, errorMessage), response);195 }196 protected void replyWithError(JsonMessage message, HttpServletResponse response) throws IOException {197 reply(SC_INTERNAL_SERVER_ERROR, message, response);198 }199 protected void reply(int code, JsonMessage message, HttpServletResponse response) throws IOException {200 response.setStatus(code);201 response.setContentType(APPLICATION_JSON.toString());202 String messageRaw = message.toJson();203 response.setContentLength(messageRaw.getBytes(UTF_8).length);204 try (OutputStream output = response.getOutputStream()) {205 IOUtils.write(messageRaw, output, UTF_8);206 }207 }208 protected HttpPost post(String target, JsonMessage message) throws IOException {...
Source:ProxyServlet.java
...5import org.slf4j.Logger;6import org.slf4j.LoggerFactory;7import org.springframework.beans.factory.annotation.Autowired;8import ru.qatools.gridrouter.json.JsonMessage;9import ru.qatools.gridrouter.json.JsonMessageFactory;10import ru.qatools.gridrouter.sessions.StatsCounter;11import javax.servlet.ServletConfig;12import javax.servlet.ServletException;13import javax.servlet.annotation.WebInitParam;14import javax.servlet.annotation.WebServlet;15import javax.servlet.http.HttpServletRequest;16import javax.servlet.http.HttpServletResponse;17import java.io.IOException;18import static java.nio.charset.StandardCharsets.UTF_8;19import static org.springframework.web.context.support.SpringBeanAutowiringSupport.processInjectionBasedOnServletContext;20import static ru.qatools.gridrouter.JsonWireUtils.*;21import static ru.qatools.gridrouter.RequestUtils.getRemoteHost;22/**23 * @author Alexander Andyashin aandryashin@yandex-team.ru24 * @author Innokenty Shuvalov innokenty@yandex-team.ru25 * @author Dmitry Baev charlie@yandex-team.ru26 * @author Artem Eroshenko eroshenkoam@yandex-team.ru27 */28@WebServlet(29 urlPatterns = {WD_HUB_SESSION + "*"},30 asyncSupported = true,31 initParams = {32 @WebInitParam(name = "timeout", value = "300000"),33 @WebInitParam(name = "idleTimeout", value = "300000")34 }35)36public class ProxyServlet extends org.eclipse.jetty.proxy.ProxyServlet {37 private static final Logger LOGGER = LoggerFactory.getLogger(ProxyServlet.class);38 @Autowired39 private transient ConfigRepository config;40 @Autowired41 private transient StatsCounter statsCounter;42 @Override43 public void init(ServletConfig config) throws ServletException {44 super.init(config);45 processInjectionBasedOnServletContext(this, config.getServletContext());46 }47 @Override48 protected void sendProxyRequest(49 HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Request proxyRequest) {50 try {51 Request request = getRequestWithoutSessionId(clientRequest, proxyRequest);52 super.sendProxyRequest(clientRequest, proxyResponse, request);53 } catch (Exception exception) {54 LOGGER.error("[REQUEST_READ_FAILURE] [{}] - could not read client request, proxying request as is",55 clientRequest.getRemoteHost(), exception);56 super.sendProxyRequest(clientRequest, proxyResponse, proxyRequest);57 }58 }59 @Override60 protected String rewriteTarget(HttpServletRequest request) {61 String uri = request.getRequestURI();62 String remoteHost = getRemoteHost(request);63 if (!isUriValid(uri)) {64 LOGGER.warn("[INVALID_SESSION_HASH] [{}] - request uri is {}", remoteHost, uri);65 return null;66 }67 String route = config.getRoute(getSessionHash(uri));68 String command = getCommand(uri);69 if (route == null) {70 LOGGER.error("[ROUTE_NOT_FOUND] [{}] - request uri is {}", remoteHost, uri);71 return null;72 }73 if (isSessionDeleteRequest(request, command)) {74 LOGGER.info("[SESSION_DELETED] [{}] [{}] [{}]", remoteHost, route, command);75 statsCounter.deleteSession(getFullSessionId(uri), route);76 } else {77 statsCounter.updateSession(getFullSessionId(uri), route);78 }79 try {80 return redirectionUrl(route, command);81 } catch (Exception exception) {82 LOGGER.error("[REDIRECTION_URL_ERROR] [{}] - error building redirection uri because of {}\n"83 + " request uri: {}\n"84 + " parsed route: {}\n"85 + " parsed command: {}",86 remoteHost, exception.toString(), uri, route, command);87 }88 return null;89 }90 protected Request getRequestWithoutSessionId(HttpServletRequest clientRequest, Request proxyRequest) throws IOException {91 String content = IOUtils.toString(clientRequest.getInputStream(), UTF_8);92 if (!content.isEmpty()) {93 String remoteHost = getRemoteHost(clientRequest);94 content = removeSessionIdSafe(content, remoteHost);95 }96 return proxyRequest.content(97 new StringContentProvider(clientRequest.getContentType(), content, UTF_8));98 }99 private String removeSessionIdSafe(String content, String remoteHost) {100 try {101 JsonMessage message = JsonMessageFactory.from(content);102 message.setSessionId(null);103 return message.toJson();104 } catch (IOException exception) {105 LOGGER.error("[UNABLE_TO_REMOVE_SESSION_ID] [{}] - could not create proxy request without session id, "106 + "proxying request as is. Request content is: {}",107 remoteHost, content, exception);108 }109 return content;110 }111}...
Source:JsonUtils.java
2import org.json.JSONObject;3import org.openqa.selenium.remote.DesiredCapabilities;4import ru.qatools.gridrouter.json.JsonCapabilities;5import ru.qatools.gridrouter.json.JsonMessage;6import ru.qatools.gridrouter.json.JsonMessageFactory;7import java.io.IOException;8import java.util.Map;9import static org.openqa.selenium.remote.CapabilityType.BROWSER_NAME;10import static org.openqa.selenium.remote.CapabilityType.PLATFORM;11import static org.openqa.selenium.remote.CapabilityType.PROXY;12import static org.openqa.selenium.remote.CapabilityType.VERSION;13/**14 * @author Innokenty Shuvalov innokenty@yandex-team.ru15 */16public final class JsonUtils {17 private JsonUtils() {18 }19 public static JsonCapabilities buildJsonCapabilities(DesiredCapabilities capabilities)20 throws IOException {21 return buildJsonMessage(capabilities).getDesiredCapabilities();22 }23 public static JsonCapabilities buildJsonCapabilities(DesiredCapabilities capabilities, String version)24 throws IOException {25 capabilities.setVersion(version);26 return buildJsonMessage(capabilities).getDesiredCapabilities();27 }28 public static JsonMessage buildJsonMessage(DesiredCapabilities capabilities) throws IOException {29 JSONObject capabilitiesObject = new JSONObject();30 Map<String, ?> capabilitiesMap = capabilities.asMap();31 capabilitiesMap.keySet().forEach(k -> capabilitiesObject.put(k, capabilitiesMap.get(k)));32 JSONObject jsonObject = new JSONObject();33 jsonObject.put("desiredCapabilities", capabilitiesObject);34 return JsonMessageFactory.from(jsonObject.toString());35 }36}...
JsonMessageFactory
Using AI Code Generation
1import ru.qatools.gridrouter.json.JsonMessageFactory;2import java.util.Map;3public class 3 {4 public static void main(String[] args) {5 JsonMessageFactory factory = new JsonMessageFactory();6 Map<String, String> map = factory.createMessage("Hello world");7 System.out.println(map);8 }9}10{type=hello, message=Hello world}11import ru.qatools.gridrouter.json.JsonMessageFactory;12import java.util.Map;13public class 4 {14 public static void main(String[] args) {15 JsonMessageFactory factory = new JsonMessageFactory();16 Map<String, String> map = factory.createMessage("Hello world", "message");17 System.out.println(map);18 }19}20{type=message, message=Hello world}21import ru.qatools.gridrouter.json.JsonMessageFactory;22import java.util.Map;23public class 5 {24 public static void main(String[] args) {25 JsonMessageFactory factory = new JsonMessageFactory();26 Map<String, String> map = factory.createMessage("Hello world", "message", "type");27 System.out.println(map);28 }29}30{type=type, message=Hello world}31import ru.qatools.gridrouter.json.JsonMessageFactory;32import java.util.Map;33public class 6 {34 public static void main(String[] args) {35 JsonMessageFactory factory = new JsonMessageFactory();36 Map<String, String> map = factory.createMessage("Hello world", "message", "type", "test");37 System.out.println(map);38 }39}40{type=type, message=Hello world, test=test}41import ru.qatools.gridrouter.json.JsonMessageFactory;42import java.util.Map;43public class 7 {44 public static void main(String[] args) {45 JsonMessageFactory factory = new JsonMessageFactory();46 Map<String, String> map = factory.createMessage("Hello world", "message", "type", "test
JsonMessageFactory
Using AI Code Generation
1import ru.qatools.gridrouter.json.JsonMessageFactory;2import ru.qatools.gridrouter.json.Message;3import java.io.IOException;4public class 3 {5 public static void main(String[] args) throws IOException {6 JsonMessageFactory factory = new JsonMessageFactory();7 Message message = factory.createMessage("Hello World");8 System.out.println(message);9 }10}11{"message":"Hello World"}12import ru.qatools.gridrouter.json.JsonMessageFactory;13import ru.qatools.gridrouter.json.Message;14import java.io.IOException;15public class 3 {16 public static void main(String[] args) throws IOException {17 JsonMessageFactory factory = new JsonMessageFactory();18 Message message = factory.createMessage("Hello World");19 System.out.println(message);20 }21}22{"message":"Hello World"}
JsonMessageFactory
Using AI Code Generation
1import ru.qatools.gridrouter.json.JsonMessage;2import ru.qatools.gridrouter.json.JsonMessageFactory;3public class 3 {4 public static void main(String[] args) throws Exception {5 JsonMessage message = JsonMessageFactory.fromJson(json);6 System.out.println(message.getMethod());7 }8}9import ru.qatools.gridrouter.json.JsonMessage;10import ru.qatools.gridrouter.json.JsonMessageFactory;11public class 4 {12 public static void main(String[] args) throws Exception {13 JsonMessage message = JsonMessageFactory.fromJson(json);14 System.out.println(message.getUrl());15 }16}17import ru.qatools.gridrouter.json.JsonMessage;18import ru.qatools.gridrouter.json.JsonMessageFactory;19public class 5 {20 public static void main(String[] args) throws Exception {21 JsonMessage message = JsonMessageFactory.fromJson(json);22 System.out.println(message.getBrowser());23 }24}25import ru.qatools.gridrouter.json.JsonMessage;26import ru.qatools.gridrouter.json.JsonMessageFactory;27public class 6 {28 public static void main(String[] args) throws Exception {29 String json = "{\"browser\":\"firefox\",\"desired
JsonMessageFactory
Using AI Code Generation
1public class 3 {2 public static void main(String[] args) {3 JsonMessageFactory factory = new JsonMessageFactory();4 Message message = factory.newMessage("Hello, World!");5 System.out.println(message);6 }7}8{"message":"Hello, World!"}9public class 4 {10 public static void main(String[] args) {11 JsonMessageFactory factory = new JsonMessageFactory();12 Message message = factory.newMessage("Hello, World!");13 System.out.println(message);14 }15}16{"message":"Hello, World!"}17public class 5 {18 public static void main(String[] args) {19 JsonMessageFactory factory = new JsonMessageFactory();20 Message message = factory.newMessage("Hello, World!");21 System.out.println(message);22 }23}24{"message":"Hello, World!"}25public class 6 {26 public static void main(String[] args) {27 JsonMessageFactory factory = new JsonMessageFactory();28 Message message = factory.newMessage("Hello, World!");29 System.out.println(message);30 }31}32{"message":"Hello, World!"}33public class 7 {34 public static void main(String[] args) {35 JsonMessageFactory factory = new JsonMessageFactory();
JsonMessageFactory
Using AI Code Generation
1import ru.qatools.gridrouter.json.JsonMessageFactory;2import ru.qatools.gridrouter.json.JsonMessage;3import java.io.IOException;4import java.net.InetAddress;5import java.net.UnknownHostException;6import java.util.HashMap;7import java.util.Map;8public class JsonMessageFactoryTest {9 public static void main(String[] args) throws UnknownHostException, IOException {10 Map<String, Object> params = new HashMap<String, Object>();11 params.put("port", "5555");12 params.put("browser", "firefox");13 params.put("browserVersion", "24");14 params.put("platform", "LINUX");15 params.put("maxInstances", "1");16 params.put("registerCycle", "5000");17 params.put("timeout", "10000");18 params.put("nodePolling", "1000");19 params.put("nodeStatusCheckTimeout", "5000");20 params.put("downPollingLimit", "2");21 JsonMessage message = JsonMessageFactory.createJsonMessage(22 "register", params, InetAddress.getLocalHost().getHostAddress(), 4444);23 System.out.println(message);24 }25}
JsonMessageFactory
Using AI Code Generation
1import ru.qatools.gridrouter.json.JsonMessageFactory;2import ru.qatools.gridrouter.json.JsonMessage;3public class JsonMessageFactoryExample1 {4 public static void main(String[] args) {5 JsonMessageFactory factory = new JsonMessageFactory();6 JsonMessage jsonMessage = factory.createJsonMessage();7 jsonMessage.setType("test");8 jsonMessage.setId("test");9 jsonMessage.setData("test");10 String jsonString = factory.toJson(jsonMessage);11 System.out.println("Json string: " + jsonString);12 }13}14Json string: {"type":"test","id":"test","data":"test"}
JsonMessageFactory
Using AI Code Generation
1package ru.qatools.gridrouter.json;2import org.json.JSONObject;3import java.io.IOException;4import java.io.InputStream;5import java.io.InputStreamReader;6import java.io.BufferedReader;7import java.io.File;8import java.io.FileInputStream;9import java.io.FileNotFoundException;10import java.util.Properties;11import java.util.Iterator;12import java.util.List;13import java.util.ArrayList;14import java.util.Map;15import java.util.HashMap;16import java.util.Set;17import java.util.HashSet;18import java.util.regex.Pattern;19import java.util.regex.Matcher;20import java.util.regex.PatternSynta
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!!