How to use getMaxSessionsAllowed method of com.paypal.selion.proxy.SeLionRemoteProxy class

Best SeLion code snippet using com.paypal.selion.proxy.SeLionRemoteProxy.getMaxSessionsAllowed

Source:SeLionRemoteProxy.java Github

copy

Full Screen

...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}...

Full Screen

Full Screen

getMaxSessionsAllowed

Using AI Code Generation

copy

Full Screen

1import com.paypal.selion.proxy.SeLionRemoteProxy;2public class RunTest {3 public static void main(String[] args) {4 SeLionRemoteProxy remoteProxy = new SeLionRemoteProxy();5 System.out.println("Max sessions allowed: " + remoteProxy.getMaxSessionsAllowed());6 }7}8import com.paypal.selion.proxy.SeLionRemoteProxy;9public class RunTest {10 public static void main(String[] args) {11 SeLionRemoteProxy remoteProxy = new SeLionRemoteProxy();12 System.out.println("Max sessions allowed: " + remoteProxy.getMaxSessionsAllowed());13 }14}

Full Screen

Full Screen

getMaxSessionsAllowed

Using AI Code Generation

copy

Full Screen

1 public void getMaxSessionsAllowedTest() {2 GridNodeConfiguration config = GridNodeConfiguration.builder().build();3 SeLionRemoteProxy proxy = new SeLionRemoteProxy(config);4 int maxSessionsAllowed = proxy.getMaxSessionsAllowed();5 Assert.assertEquals(maxSessionsAllowed, 1);6 }7}8[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ selion-grid ---9[INFO] --- maven-source-plugin:2.4:jar-no-fork (attach-sources) @ selion-grid ---10[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ selion-grid ---

Full Screen

Full Screen

getMaxSessionsAllowed

Using AI Code Generation

copy

Full Screen

1private static final int MAX_SESSIONS = 5;2public void onRegistration() {3 super.onRegistration();4 try {5 Field maxSessions = getClass().getSuperclass().getDeclaredField("maxSessions");6 maxSessions.setAccessible(true);7 maxSessions.set(this, getMaxSessionsAllowed(MAX_SESSIONS));8 } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {9 e.printStackTrace();10 }11}12private static final int MAX_SESSIONS = 5;13public void onRegistration() {14 super.onRegistration();15 try {16 Field maxSessions = getClass().getSuperclass().getDeclaredField("maxSessions");17 maxSessions.setAccessible(true);18 maxSessions.set(this, getMaxSessionsAllowed(MAX_SESSIONS));19 } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {20 e.printStackTrace();21 }22}23private static final int MAX_SESSIONS = 5;24public void onRegistration() {25 super.onRegistration();26 try {27 Field maxSessions = getClass().getSuperclass().getDeclaredField("maxSessions");28 maxSessions.setAccessible(true);29 maxSessions.set(this, getMaxSessionsAllowed(MAX_SESSIONS));30 } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {31 e.printStackTrace();32 }33}34private static final int MAX_SESSIONS = 5;35public void onRegistration() {36 super.onRegistration();37 try {38 Field maxSessions = getClass().getSuperclass().getDeclaredField

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful