Best SeLion code snippet using com.paypal.selion.proxy.SeLionRemoteProxy.isEnabledMaxUniqueSessions
Source:SeLionRemoteProxy.java
...138 StringBuffer info = new StringBuffer();139 info.append("New proxy instantiated for the node ").append(machine).append(":").append(port);140 proxyLogger.info(info.toString());141 info = new StringBuffer();142 if (isEnabledMaxUniqueSessions()) {143 info.append("SeLionRemoteProxy will attempt to recycle the node ");144 info.append(machine).append(":").append(port).append(" after ").append(getMaxSessionsAllowed())145 .append(" unique sessions");146 } else {147 info.append("SeLionRemoteProxy will not attempt to recycle the node ");148 info.append(machine).append(":").append(port).append(" based on unique session counting.");149 }150 proxyLogger.info(info.toString());151 // Enable the cache to store the browser information only when the152 // "com.paypal.selion.grid.servlets.GridStatistics" is enabled - results in153 // better memory management if the servlet is not loaded154 if (isSupportedOnHub(GridStatistics.class)) {155 updateBrowserCache(request);156 }157 // detect presence of SeLion servlet capabilities on proxy158 canForceShutdown = isSupportedOnNode(NodeForceRestartServlet.class);159 canAutoUpgrade = isSupportedOnNode(NodeAutoUpgradeServlet.class);160 canViewLogs = isSupportedOnNode(LogServlet.class);161 }162 /**163 * Determine if the hub supports the servlet in question by looking at the registry configuration.164 * @param servlet165 * the {@link HttpServlet} to ping166 * @return <code>true</code> or <code>false</code>167 */168 private boolean isSupportedOnHub(Class<? extends HttpServlet> servlet) {169 LOGGER.entering();170 final boolean response = getRegistry().getHub().getConfiguration().servlets.contains(servlet.getCanonicalName());171 LOGGER.exiting(response);172 return response;173 }174 /**175 * Determine if the remote proxy supports the servlet in question by sending a http request to the remote. The176 * proxy configuration could also be used to make a similar decision. This approach allows the remote to use a177 * servlet which implements the same functionality as the `servlet` expected but does not necessarily reside in the178 * same namespace. This method expects the `servlet` to return HTTP 200 OK as an indication that the remote proxy179 * supports the `servlet` in question.180 *181 * @param servlet182 * the {@link HttpServlet} to ping183 * @return <code>true</code> or <code>false</code>184 */185 private boolean isSupportedOnNode(Class<? extends HttpServlet> servlet) {186 LOGGER.entering();187 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT)188 .setSocketTimeout(CONNECTION_TIMEOUT).build();189 CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();190 String url = String.format("http://%s:%d/extra/%s", machine, getRemoteHost().getPort(),191 servlet.getSimpleName());192 try {193 HttpGet get = new HttpGet(url);194 final HttpResponse getResponse = client.execute(get);195 if (getResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {196 proxyLogger.warning("Node " + getId() + " does not have or support " + servlet.getSimpleName());197 LOGGER.exiting(false);198 return false;199 }200 } catch (IOException e) {201 LOGGER.log(Level.SEVERE, e.getMessage(), e);202 LOGGER.exiting(false);203 return false;204 } finally {205 try {206 client.close();207 } catch (IOException e) {208 LOGGER.log(Level.SEVERE, e.getMessage(), e);209 }210 }211 LOGGER.exiting(true);212 return true;213 }214 private HttpResponse sendToNodeServlet(Class<? extends HttpServlet> servlet, List<NameValuePair> nvps) {215 LOGGER.entering();216 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT)217 .setSocketTimeout(CONNECTION_TIMEOUT).build();218 CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();219 String url = String.format("http://%s:%d/extra/%s", machine, this.getRemoteHost().getPort(),220 servlet.getSimpleName());221 HttpResponse postResponse = null;222 try {223 HttpPost post = new HttpPost(url);224 post.setEntity(new UrlEncodedFormEntity(nvps));225 postResponse = client.execute(post);226 } catch (IOException e) {227 LOGGER.log(Level.SEVERE, e.getMessage(), e);228 } finally {229 try {230 client.close();231 } catch (IOException e) {232 LOGGER.log(Level.SEVERE, e.getMessage(), e);233 }234 }235 LOGGER.exiting(postResponse);236 return postResponse;237 }238 /**239 * Upgrades the node by calling {@link NodeAutoUpgradeServlet} and then {@link #requestNodeShutdown}240 *241 * @param downloadJSON242 * the download.json to install on node243 * @return <code>true</code> on success. <code>false</code> when an error occured.244 */245 public boolean upgradeNode(String downloadJSON) {246 LOGGER.entering(downloadJSON);247 // verify the servlet is supported on the node248 if (!supportsAutoUpgrade()) {249 LOGGER.exiting(false);250 return false;251 }252 // call the NodeAutoUpgradeServlet on the node253 proxyLogger.fine("Upgrading node " + getId());254 List<NameValuePair> nvps = new ArrayList<>();255 nvps.add(new BasicNameValuePair(NodeAutoUpgradeServlet.TOKEN_PARAMETER,256 NodeAutoUpgradeServlet.CONFIGURED_TOKEN_VALUE));257 NameValuePair jsonNVP = new BasicNameValuePair(GridAutoUpgradeDelegateServlet.PARAM_JSON, downloadJSON);258 nvps.add(jsonNVP);259 HttpResponse response = sendToNodeServlet(NodeAutoUpgradeServlet.class, nvps);260 if (response == null) {261 proxyLogger.warning("Node " + getId() + " failed to upgrade and returned a null response.");262 LOGGER.exiting(false);263 return false;264 }265 final int responseStatusCode = response.getStatusLine().getStatusCode();266 if (responseStatusCode != HttpStatus.SC_OK) {267 proxyLogger.warning("Node " + getId() + " failed to upgrade and returned HTTP " + responseStatusCode);268 LOGGER.exiting(false);269 return false;270 }271 requestNodeShutdown();272 LOGGER.exiting(true);273 return true;274 }275 /**276 * @return whether the proxy has reached the max unique sessions277 */278 private boolean isMaxUniqueSessionsReached() {279 if (!isEnabledMaxUniqueSessions()) {280 return false;281 }282 return totalSessionsStarted >= getMaxSessionsAllowed();283 }284 @Override285 public TestSession getNewSession(Map<String, Object> requestedCapability) {286 LOGGER.entering();287 // verification should be before lock to avoid unnecessarily acquiring lock288 if (isMaxUniqueSessionsReached() || scheduledShutdown) {289 LOGGER.exiting(null);290 return logSessionInfo();291 }292 try {293 accessLock.lock();294 // As per double-checked locking pattern need to have check once again295 // to avoid spawning additional session then maxSessionAllowed296 if (isMaxUniqueSessionsReached() || scheduledShutdown) {297 LOGGER.exiting(null);298 return logSessionInfo();299 }300 TestSession session = super.getNewSession(requestedCapability);301 if (session != null) {302 // count ONLY if the session was a valid one303 totalSessionsStarted++;304 if (isMaxUniqueSessionsReached()) {305 startNodeRecycleThread();306 }307 proxyLogger.fine("Beginning session #" + totalSessionsStarted + " (" + session.toString() + ")");308 }309 LOGGER.exiting((session != null) ? session.toString() : null);310 return session;311 } finally {312 accessLock.unlock();313 }314 }315 private TestSession logSessionInfo() {316 proxyLogger.fine("Was max sessions reached? " + (isMaxUniqueSessionsReached()) + " on node " + getId());317 proxyLogger.fine("Was this a scheduled shutdown? " + (scheduledShutdown) + " on node " + getId());318 return null;319 }320 private void startNodeRecycleThread() {321 if (!getNodeRecycleThread().isAlive()) {322 getNodeRecycleThread().start();323 }324 }325 private void stopNodeRecycleThread() {326 if (getNodeRecycleThread().isAlive()) {327 try {328 getNodeRecycleThread().shutdown();329 getNodeRecycleThread().join(2000); // Wait no longer than 2x the recycle thread's loop330 } catch (InterruptedException e) { // NOSONAR331 // ignore332 }333 }334 }335 private void updateBrowserCache(RegistrationRequest request) throws MalformedURLException {336 // Update the browser information cache. Used by GridStatics servlet337 for (MutableCapabilities desiredCapabilities : request.getConfiguration().capabilities) {338 Map<String, ?> capabilitiesMap = desiredCapabilities.asMap();339 String browserName = capabilitiesMap.get(CapabilityType.BROWSER_NAME).toString();340 String maxInstancesAsString = capabilitiesMap.get("maxInstances").toString();341 if (StringUtils.isNotBlank(browserName) && StringUtils.isNotBlank(maxInstancesAsString)) {342 int maxInstances = Integer.valueOf(maxInstancesAsString);343 BrowserInformationCache cache = BrowserInformationCache.getInstance();344 cache.updateBrowserInfo(getRemoteHost(), browserName, maxInstances);345 }346 }347 }348 @Override349 public void afterSession(TestSession session) {350 LOGGER.entering();351 totalSessionsCompleted++;352 proxyLogger.fine("Completed session #" + totalSessionsCompleted + " (" + session.toString() + ")");353 proxyLogger.fine("Total number of slots used: " + getTotalUsed() + " on node: " + getId());354 LOGGER.exiting();355 }356 /**357 * Gracefully shuts the node down by;<br>358 * <br>359 * 1. Stops accepting new sessions<br>360 * 2. Waits for sessions to complete<br>361 * 3. Calls {@link #forceNodeShutdown}<br>362 */363 public void requestNodeShutdown() {364 LOGGER.entering();365 scheduledShutdown = true;366 startNodeRecycleThread();367 LOGGER.exiting();368 }369 /**370 * Forcefully shuts the node down by calling {@link NodeForceRestartServlet}371 */372 public synchronized void forceNodeShutdown() {373 LOGGER.entering();374 // stop the node recycle thread375 stopNodeRecycleThread();376 // verify the servlet is supported on the node377 if (!canForceShutdown) {378 // allow this proxy to keep going379 disableMaxSessions();380 scheduledShutdown = false;381 LOGGER.exiting();382 return;383 }384 // clean up the test slots385 for (TestSlot slot : getTestSlots()) {386 if (slot.getSession() != null) {387 totalSessionsCompleted++;388 proxyLogger.info("Timing out session #" + totalSessionsCompleted + " (" + slot.getSession().toString()389 + ")");390 getRegistry().forceRelease(slot, SessionTerminationReason.TIMEOUT);391 }392 }393 // call the node servlet394 List<NameValuePair> nvps = new ArrayList<>();395 nvps.add(new BasicNameValuePair(NodeForceRestartServlet.TOKEN_PARAMETER,396 NodeForceRestartServlet.CONFIGURED_TOKEN_VALUE));397 HttpResponse response = sendToNodeServlet(NodeForceRestartServlet.class, nvps);398 if (response == null) {399 proxyLogger.warning("Node " + getId() + " failed to shutdown and returned a null response.");400 // stop the polling thread, mark this proxy as down, force this proxy to re-register401 teardown("it failed to shutdown and must re-register");402 LOGGER.exiting();403 return;404 }405 final int responseStatusCode = response.getStatusLine().getStatusCode();406 if (responseStatusCode != HttpStatus.SC_OK) {407 proxyLogger.warning("Node " + getId() + " did not shutdown and returned HTTP " + responseStatusCode);408 // stop the polling thread, mark this proxy as down, force this proxy to re-register409 teardown("it failed to shutdown and must re-register");410 LOGGER.exiting();411 return;412 }413 // stop the polling thread, mark this proxy as down414 teardown("it is shutdown");415 proxyLogger.info("Node " + getId() + " shutdown successfully.");416 LOGGER.exiting();417 }418 private void teardown(String reason) {419 addNewEvent(new RemoteUnregisterException(String.format("Unregistering node %s because %s.",420 getId(), reason)));421 teardown();422 }423 /**424 * Thread will recycle the node when all active sessions are completed425 */426 class NodeRecycleThread extends Thread {427 private static final int DEFAULT_TIMEOUT = 0; // Waits forever428 private volatile boolean running;429 private final String nodeId;430 NodeRecycleThread(String nodeId) {431 super();432 running = false;433 this.nodeId = nodeId;434 }435 @Override436 public void run() {437 LOGGER.entering();438 running = true;439 int timeout = getThreadWaitTimeout();440 int expired = 0;441 proxyLogger.fine("Started NodeRecycleThread with " + ((timeout == 0) ? "no" : "a " + timeout + " second")442 + " timeout for node " + nodeId);443 while (keepLooping(expired, timeout)) {444 try {445 sleep(1000);446 expired += 1;447 } catch (InterruptedException e) {448 if (running) {449 // SEVERE, only if shutdown() was not called450 LOGGER.log(Level.SEVERE, e.getMessage(), e);451 }452 running = false;453 proxyLogger.warning("NodeRecycleThread was interrupted.");454 LOGGER.exiting();455 return;456 }457 }458 if (wasExpired(expired, timeout)) {459 proxyLogger.info("Timeout occurred while waiting for sessions to complete. Shutting down the node.");460 } else {461 proxyLogger.info("All sessions are complete. Shutting down the node.");462 }463 forceNodeShutdown();464 LOGGER.exiting();465 }466 int getThreadWaitTimeout() {467 final String key = "nodeRecycleThreadWaitTimeout";468 return config.custom.containsKey(key) ? Integer.parseInt(config.custom.get(key)) : DEFAULT_TIMEOUT;469 }470 private boolean keepLooping(int expired, int timeout) {471 return (getTotalUsed() > 0) && running && ((expired < timeout) || (timeout == 0));472 }473 private boolean wasExpired(int expired, int timeout) {474 return (expired >= timeout) && (timeout != 0);475 }476 public void shutdown() {477 LOGGER.entering();478 running = false;479 proxyLogger.fine("Shutting down NodeRecycleThread for node " + nodeId);480 interrupt();481 LOGGER.exiting();482 }483 }484 /**485 * @return the {@link NodeRecycleThread} associated with this proxy486 */487 private NodeRecycleThread getNodeRecycleThread() {488 return nodeRecycleThread;489 }490 /**491 * disables the max session count for this node.492 */493 private void disableMaxSessions() {494 proxyLogger.warning("Disabling max unique sessions for Node " + getId());495 config.custom.put("uniqueSessionCount", "-1");496 }497 /**498 * @return an integer value which represents the number of unique sessions this proxy allows for before499 * automatically spinning up a {@link NodeRecycleThread}500 */501 private int getMaxSessionsAllowed() {502 final String key = "uniqueSessionCount";503 return config.custom.containsKey(key) ? Integer.parseInt(config.custom.get(key)) : DEFAULT_MAX_SESSIONS_ALLOWED;504 }505 /**506 * @return total uptime since proxy came online in minutes507 */508 public long getUptimeInMinutes() {509 return TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - proxyStartMillis);510 }511 /**512 * @return total number of sessions completed since proxy came online513 */514 public int getTotalSessionsComplete() {515 return totalSessionsCompleted;516 }517 /**518 * @return total number of sessions started since proxy came online519 */520 public int getTotalSessionsStarted() {521 return totalSessionsStarted;522 }523 /**524 * @return <code>true</code> or <code>false</code>, whether the proxy is scheduled for recycle525 */526 public boolean isScheduledForRecycle() {527 return getNodeRecycleThread().isAlive();528 }529 /**530 * @return whether the proxy supports/has running {@link NodeForceRestartServlet}531 */532 public boolean supportsForceShutdown() {533 return canForceShutdown;534 }535 /**536 * @return whether the proxy supports/has running {@link NodeAutoUpgradeServlet}537 */538 public boolean supportsAutoUpgrade() {539 return canAutoUpgrade;540 }541 /**542 * @return whether the proxy supports/has running {@link LogServlet}543 */544 public boolean supportsViewLogs() {545 return canViewLogs;546 }547 /**548 * @return whether the proxy is enabled to limit the number of unique sessions before triggering a graceful shutdown549 */550 private boolean isEnabledMaxUniqueSessions() {551 return (getMaxSessionsAllowed() > 0);552 }553}...
isEnabledMaxUniqueSessions
Using AI Code Generation
1import com.paypal.selion.proxy.SeLionRemoteProxy;2public class MyProxy extends SeLionRemoteProxy {3 public MyProxy(RegistrationRequest request, Registry registry) {4 super(request, registry);5 }6 public boolean isReadyToUse() {7 return isEnabledMaxUniqueSessions();8 }9}
isEnabledMaxUniqueSessions
Using AI Code Generation
1if (proxy.isEnabledMaxUniqueSessions()) {2 int maxUniqueSessions = proxy.getMaxUniqueSessions();3 int uniqueSessionCount = proxy.getUniqueSessionCount();4 if (uniqueSessionCount >= maxUniqueSessions) {5 return false;6 }7}8return true;
isEnabledMaxUniqueSessions
Using AI Code Generation
1import org.openqa.grid.common.RegistrationRequest;2import org.openqa.grid.internal.Registry;3import org.openqa.grid.internal.RemoteProxy;4import org.openqa.grid.internal.TestSession;5import org.openqa.grid.selenium.proxy.DefaultRemoteProxy;6import com.paypal.selion.proxy.SeLionRemoteProxy;7import java.util.Map;8public class SeLionRemoteProxy extends DefaultRemoteProxy {9 public SeLionRemoteProxy(RegistrationRequest request, Registry registry) {10 super(request, registry);11 }12 public TestSession getNewSession(Map<String, Object> requestedCapability) {13 if (isEnabledMaxUniqueSessions()) {14 return super.getNewSession(requestedCapability);15 }16 return null;17 }18 private boolean isEnabledMaxUniqueSessions() {19 RemoteProxy remoteProxy = this;20 int maxUniqueSessions = 0;21 if (remoteProxy.getConfig().capabilities.size() > 0) {22 if (remoteProxy.getConfig().capabilities.get(0).get("maxUniqueSessions") != null) {23 maxUniqueSessions = (Integer) remoteProxy.getConfig().capabilities.get(0).get("maxUniqueSessions");24 }25 }26 if (maxUniqueSessions > 0) {27 if (remoteProxy.getNumberOfTestSessions() < maxUniqueSessions) {28 return true;29 } else {30 return false;31 }32 } else {33 return true;34 }35 }36}37{38 {39 }40 "configuration": {41 }42}
isEnabledMaxUniqueSessions
Using AI Code Generation
1public boolean isEnabledMaxUniqueSessions(com.paypal.selion.proxy.SeLionRemoteProxy proxy) {2 return proxy.isEnabledMaxUniqueSessions();3}4public boolean isEnabledMaxSessionCount(com.paypal.selion.proxy.SeLionRemoteProxy proxy) {5 return proxy.isEnabledMaxSessionCount();6}7public boolean isEnabledMaxSessionCount(com.paypal.selion.proxy.SeLionRemoteProxy proxy) {8 return proxy.isEnabledMaxSessionCount();9}
isEnabledMaxUniqueSessions
Using AI Code Generation
1public class MaxUniqueSessionsListener extends TestListenerAdapter {2 private static final Logger LOGGER = LoggerFactory.getLogger(MaxUniqueSessionsListener.class);3 private static final String MAX_UNIQUE_SESSIONS = "maxUniqueSessions";4 public void onTestStart(ITestResult result) {5 if (LOGGER.isDebugEnabled()) {6 LOGGER.debug("onTestStart() method of MaxUniqueSessionsListener class is invoked");7 }8 String testName = result.getName();9 String testClassName = result.getTestClass().getName();10 LOGGER.info("Test Name: " + testName);11 LOGGER.info("Test Class Name: " + testClassName);12 String deviceName = getDeviceName(testName, testClassName);13 LOGGER.info("Device Name: " + deviceName);14 if (deviceName != null) {15 boolean isDeviceAvailable = isEnabledMaxUniqueSessions(deviceName);16 if (!isDeviceAvailable) {17 LOGGER.info("Device is already used by another test session. Hence, this test session is terminated");18 result.setStatus(ITestResult.SKIP);19 }20 }21 }22 private String getDeviceName(String testName, String testClassName) {23 String deviceName = null;24 try {25 Class<?> testClass = Class.forName(testClassName);26 Method method = testClass.getMethod(testName);27 Annotation[][] annotations = method.getParameterAnnotations();28 if (annotations.length > 0) {29 for (Annotation[] annotation : annotations) {30 for (Annotation an : annotation) {31 if (an instanceof Device) {32 deviceName = ((Device) an).value();33 break;34 }35 }36 }37 }38 } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {39 LOGGER.error("Exception occurred while getting the device name", e);40 }41 return deviceName;42 }43 private boolean isEnabledMaxUniqueSessions(String deviceName) {44 boolean isEnabledMaxUniqueSessions = false;45 try {46 Class<?> selionRemoteProxy = Class.forName("com.paypal.selion.proxy.SeLionRemoteProxy");
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!!