How to use shutdownGracefully method of org.openqa.selenium.concurrent.ExecutorServices class

Best Selenium code snippet using org.openqa.selenium.concurrent.ExecutorServices.shutdownGracefully

Source:LocalNewSessionQueue.java Github

copy

Full Screen

1package org.openqa.selenium.grid.sessionqueue.local;2import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;3import static java.util.concurrent.TimeUnit.MILLISECONDS;4import static org.openqa.selenium.concurrent.ExecutorServices.shutdownGracefully;5import com.google.common.annotations.VisibleForTesting;6import com.google.common.collect.ImmutableMap;7import com.google.common.collect.ImmutableSet;8import org.openqa.selenium.Capabilities;9import org.openqa.selenium.SessionNotCreatedException;10import org.openqa.selenium.concurrent.GuardedRunnable;11import org.openqa.selenium.events.EventBus;12import org.openqa.selenium.grid.config.Config;13import org.openqa.selenium.grid.data.CreateSessionResponse;14import org.openqa.selenium.grid.data.NewSessionErrorResponse;15import org.openqa.selenium.grid.data.NewSessionRejectedEvent;16import org.openqa.selenium.grid.data.NewSessionRequestEvent;17import org.openqa.selenium.grid.data.RequestId;18import org.openqa.selenium.grid.data.SessionRequest;19import org.openqa.selenium.grid.data.SessionRequestCapability;20import org.openqa.selenium.grid.data.SlotMatcher;21import org.openqa.selenium.grid.data.TraceSessionRequest;22import org.openqa.selenium.grid.distributor.config.DistributorOptions;23import org.openqa.selenium.grid.jmx.JMXHelper;24import org.openqa.selenium.grid.jmx.ManagedAttribute;25import org.openqa.selenium.grid.jmx.ManagedService;26import org.openqa.selenium.grid.log.LoggingOptions;27import org.openqa.selenium.grid.security.Secret;28import org.openqa.selenium.grid.security.SecretOptions;29import org.openqa.selenium.grid.server.EventBusOptions;30import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;31import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueueOptions;32import org.openqa.selenium.internal.Either;33import org.openqa.selenium.internal.Require;34import org.openqa.selenium.remote.http.Contents;35import org.openqa.selenium.remote.http.HttpResponse;36import org.openqa.selenium.remote.tracing.Span;37import org.openqa.selenium.remote.tracing.TraceContext;38import org.openqa.selenium.remote.tracing.Tracer;39import java.io.Closeable;40import java.io.IOException;41import java.time.Duration;42import java.time.Instant;43import java.util.Deque;44import java.util.Iterator;45import java.util.List;46import java.util.Map;47import java.util.Optional;48import java.util.Set;49import java.util.concurrent.ConcurrentHashMap;50import java.util.concurrent.ConcurrentLinkedDeque;51import java.util.concurrent.CountDownLatch;52import java.util.concurrent.Executors;53import java.util.concurrent.ScheduledExecutorService;54import java.util.concurrent.locks.Lock;55import java.util.concurrent.locks.ReadWriteLock;56import java.util.concurrent.locks.ReentrantReadWriteLock;57import java.util.function.Predicate;58import java.util.stream.Collectors;59/**60 * An in-memory implementation of the list of new session requests.61 * <p>62 * The lifecycle of a request can be described as:63 * <ol>64 * <li>User adds an item on to the queue using {@link #addToQueue(SessionRequest)}. This65 * will block until the request completes in some way.66 * <li>After being added, a {@link NewSessionRequestEvent} is fired. Listeners should use67 * this as an indication to call {@link #remove(RequestId)} to get the session request.68 * <li>If the session request is completed, then {@link #complete(RequestId, Either)} must69 * be called. This will not only ensure that {@link #addToQueue(SessionRequest)}70 * returns, but will also fire a {@link NewSessionRejectedEvent} if the session was71 * rejected. Positive completions of events are assumed to be notified on the event bus72 * by other listeners.73 * <li>If the request cannot be handled right now, call74 * {@link #retryAddToQueue(SessionRequest)} to return the session request to the front75 * of the queue.76 * </ol>77 * <p>78 * There is a background thread that will reap {@link SessionRequest}s that have timed out.79 * This means that a request can either complete by a listener calling80 * {@link #complete(RequestId, Either)} directly, or by being reaped by the thread.81 */82@ManagedService(objectName = "org.seleniumhq.grid:type=SessionQueue,name=LocalSessionQueue",83 description = "New session queue")84public class LocalNewSessionQueue extends NewSessionQueue implements Closeable {85 private static final String NAME = "Local New Session Queue";86 private final EventBus bus;87 private final SlotMatcher slotMatcher;88 private final Duration requestTimeout;89 private final Map<RequestId, Data> requests;90 private final Map<RequestId, TraceContext> contexts;91 private final Deque<SessionRequest> queue;92 private final ReadWriteLock lock = new ReentrantReadWriteLock();93 private final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(r -> {94 Thread thread = new Thread(r);95 thread.setDaemon(true);96 thread.setName(NAME);97 return thread;98 });99 public LocalNewSessionQueue(100 Tracer tracer,101 EventBus bus,102 SlotMatcher slotMatcher,103 Duration retryPeriod,104 Duration requestTimeout,105 Secret registrationSecret) {106 super(tracer, registrationSecret);107 this.slotMatcher = Require.nonNull("Slot matcher", slotMatcher);108 this.bus = Require.nonNull("Event bus", bus);109 Require.nonNegative("Retry period", retryPeriod);110 this.requestTimeout = Require.positive("Request timeout", requestTimeout);111 this.requests = new ConcurrentHashMap<>();112 this.queue = new ConcurrentLinkedDeque<>();113 this.contexts = new ConcurrentHashMap<>();114 // if retryPeriod is 0, we will schedule timeout checks every 15 seconds115 // there is no need to run this more often116 long period = retryPeriod.isZero() ? 15000 : retryPeriod.toMillis();117 service.scheduleAtFixedRate(118 GuardedRunnable.guard(this::timeoutSessions),119 retryPeriod.toMillis(),120 period, MILLISECONDS);121 new JMXHelper().register(this);122 }123 public static NewSessionQueue create(Config config) {124 LoggingOptions loggingOptions = new LoggingOptions(config);125 Tracer tracer = loggingOptions.getTracer();126 EventBusOptions eventBusOptions = new EventBusOptions(config);127 NewSessionQueueOptions newSessionQueueOptions = new NewSessionQueueOptions(config);128 SecretOptions secretOptions = new SecretOptions(config);129 SlotMatcher slotMatcher = new DistributorOptions(config).getSlotMatcher();130 return new LocalNewSessionQueue(131 tracer,132 eventBusOptions.getEventBus(),133 slotMatcher,134 newSessionQueueOptions.getSessionRequestRetryInterval(),135 newSessionQueueOptions.getSessionRequestTimeout(),136 secretOptions.getRegistrationSecret());137 }138 private void timeoutSessions() {139 Instant now = Instant.now();140 Lock readLock = lock.readLock();141 readLock.lock();142 Set<RequestId> ids;143 try {144 ids = requests.entrySet().stream()145 .filter(entry -> isTimedOut(now, entry.getValue()))146 .map(Map.Entry::getKey)147 .collect(ImmutableSet.toImmutableSet());148 } finally {149 readLock.unlock();150 }151 ids.forEach(this::failDueToTimeout);152 }153 private boolean isTimedOut(Instant now, Data data) {154 return data.endTime.isBefore(now);155 }156 @Override157 public HttpResponse addToQueue(SessionRequest request) {158 Require.nonNull("New session request", request);159 Require.nonNull("Request id", request.getRequestId());160 TraceContext context = TraceSessionRequest.extract(tracer, request);161 try (Span ignored = context.createSpan("sessionqueue.add_to_queue")) {162 contexts.put(request.getRequestId(), context);163 Data data = injectIntoQueue(request);164 if (isTimedOut(Instant.now(), data)) {165 failDueToTimeout(request.getRequestId());166 }167 Either<SessionNotCreatedException, CreateSessionResponse> result;168 try {169 if (data.latch.await(requestTimeout.toMillis(), MILLISECONDS)) {170 result = data.result;171 } else {172 result = Either.left(new SessionNotCreatedException("New session request timed out"));173 }174 } catch (InterruptedException e) {175 Thread.currentThread().interrupt();176 result = Either.left(new SessionNotCreatedException("Interrupted when creating the session", e));177 } catch (RuntimeException e) {178 result = Either.left(new SessionNotCreatedException("An error occurred creating the session", e));179 }180 Lock writeLock = this.lock.writeLock();181 writeLock.lock();182 try {183 requests.remove(request.getRequestId());184 queue.remove(request);185 } finally {186 writeLock.unlock();187 }188 HttpResponse res = new HttpResponse();189 if (result.isRight()) {190 res.setContent(Contents.bytes(result.right().getDownstreamEncodedResponse()));191 } else {192 res.setStatus(HTTP_INTERNAL_ERROR)193 .setContent(Contents.asJson(ImmutableMap.of(194 "value", ImmutableMap.of("error", "session not created",195 "message", result.left().getMessage(),196 "stacktrace", result.left().getStackTrace()))));197 }198 return res;199 }200 }201 @VisibleForTesting202 Data injectIntoQueue(SessionRequest request) {203 Require.nonNull("Session request", request);204 Data data = new Data(request.getEnqueued());205 Lock writeLock = lock.writeLock();206 writeLock.lock();207 try {208 requests.put(request.getRequestId(), data);209 queue.addLast(request);210 } finally {211 writeLock.unlock();212 }213 bus.fire(new NewSessionRequestEvent(request.getRequestId()));214 return data;215 }216 @Override217 public boolean retryAddToQueue(SessionRequest request) {218 Require.nonNull("New session request", request);219 boolean added;220 TraceContext context = contexts.getOrDefault(request.getRequestId(), tracer.getCurrentContext());221 try (Span ignored = context.createSpan("sessionqueue.retry")) {222 Lock writeLock = lock.writeLock();223 writeLock.lock();224 try {225 if (!requests.containsKey(request.getRequestId())) {226 return false;227 }228 if (queue.contains(request)) {229 // No need to re-add this230 return true;231 } else {232 added = queue.offerFirst(request);233 }234 } finally {235 writeLock.unlock();236 }237 if (added) {238 bus.fire(new NewSessionRequestEvent(request.getRequestId()));239 }240 return added;241 }242 }243 @Override244 public Optional<SessionRequest> remove(RequestId reqId) {245 Require.nonNull("Request ID", reqId);246 Lock writeLock = lock.writeLock();247 writeLock.lock();248 try {249 Iterator<SessionRequest> iterator = queue.iterator();250 while (iterator.hasNext()) {251 SessionRequest req = iterator.next();252 if (reqId.equals(req.getRequestId())) {253 iterator.remove();254 return Optional.of(req);255 }256 }257 return Optional.empty();258 } finally {259 writeLock.unlock();260 }261 }262 @Override263 public Optional<SessionRequest> getNextAvailable(Set<Capabilities> stereotypes) {264 Require.nonNull("Stereotypes", stereotypes);265 Predicate<Capabilities> matchesStereotype =266 caps -> stereotypes.stream().anyMatch(stereotype -> slotMatcher.matches(stereotype, caps));267 Lock writeLock = lock.writeLock();268 writeLock.lock();269 try {270 Optional<SessionRequest> maybeRequest =271 queue.stream()272 .filter(req -> req.getDesiredCapabilities().stream().anyMatch(matchesStereotype))273 .findFirst();274 maybeRequest.ifPresent(req -> this.remove(req.getRequestId()));275 return maybeRequest;276 } finally {277 writeLock.unlock();278 }279 }280 @Override281 public void complete(RequestId reqId, Either<SessionNotCreatedException, CreateSessionResponse> result) {282 Require.nonNull("New session request", reqId);283 Require.nonNull("Result", result);284 TraceContext context = contexts.getOrDefault(reqId, tracer.getCurrentContext());285 try (Span ignored = context.createSpan("sessionqueue.completed")) {286 Lock readLock = lock.readLock();287 readLock.lock();288 Data data;289 try {290 data = requests.get(reqId);291 } finally {292 readLock.unlock();293 }294 if (data == null) {295 return;296 }297 Lock writeLock = lock.writeLock();298 writeLock.lock();299 try {300 requests.remove(reqId);301 queue.removeIf(req -> reqId.equals(req.getRequestId()));302 contexts.remove(reqId);303 } finally {304 writeLock.unlock();305 }306 if (result.isLeft()) {307 bus.fire(new NewSessionRejectedEvent(new NewSessionErrorResponse(reqId, result.left().getMessage())));308 }309 data.setResult(result);310 }311 }312 @Override313 public int clearQueue() {314 Lock writeLock = lock.writeLock();315 writeLock.lock();316 try {317 int size = queue.size();318 queue.clear();319 requests.forEach((reqId, data) -> {320 data.setResult(Either.left(new SessionNotCreatedException("Request queue was cleared")));321 bus.fire(new NewSessionRejectedEvent(322 new NewSessionErrorResponse(reqId, "New session queue was forcibly cleared")));323 });324 requests.clear();325 return size;326 } finally {327 writeLock.unlock();328 }329 }330 @Override331 public List<SessionRequestCapability> getQueueContents() {332 Lock readLock = lock.readLock();333 readLock.lock();334 try {335 return queue.stream()336 .map(req ->337 new SessionRequestCapability(req.getRequestId(), req.getDesiredCapabilities()))338 .collect(Collectors.toList());339 } finally {340 readLock.unlock();341 }342 }343 @ManagedAttribute(name = "NewSessionQueueSize")344 public int getQueueSize() {345 return queue.size();346 }347 @Override348 public boolean isReady() {349 return true;350 }351 @Override352 public void close() throws IOException {353 shutdownGracefully(NAME, service);354 }355 private void failDueToTimeout(RequestId reqId) {356 complete(reqId, Either.left(new SessionNotCreatedException("Timed out creating session")));357 }358 private class Data {359 public final Instant endTime;360 private final CountDownLatch latch = new CountDownLatch(1);361 public Either<SessionNotCreatedException, CreateSessionResponse> result;362 private boolean complete;363 public Data(Instant enqueued) {364 this.endTime = enqueued.plus(requestTimeout);365 this.result = Either.left(new SessionNotCreatedException("Session not created"));366 }367 public synchronized void setResult(Either<SessionNotCreatedException, CreateSessionResponse> result) {...

Full Screen

Full Screen

Source:DriverService.java Github

copy

Full Screen

...16// under the License.17package org.openqa.selenium.remote.service;18import static java.util.Collections.emptyMap;19import static java.util.concurrent.TimeUnit.SECONDS;20import static org.openqa.selenium.concurrent.ExecutorServices.shutdownGracefully;21import com.google.common.collect.ImmutableMap;22import org.openqa.selenium.Beta;23import org.openqa.selenium.Capabilities;24import org.openqa.selenium.WebDriverException;25import org.openqa.selenium.internal.Require;26import org.openqa.selenium.net.PortProber;27import org.openqa.selenium.net.UrlChecker;28import org.openqa.selenium.os.CommandLine;29import org.openqa.selenium.os.ExecutableFinder;30import java.io.Closeable;31import java.io.File;32import java.io.FileOutputStream;33import java.io.IOException;34import java.io.OutputStream;35import java.net.MalformedURLException;36import java.net.URL;37import java.time.Duration;38import java.util.List;39import java.util.Map;40import java.util.concurrent.CompletableFuture;41import java.util.concurrent.ExecutionException;42import java.util.concurrent.ExecutorService;43import java.util.concurrent.Executors;44import java.util.concurrent.TimeUnit;45import java.util.concurrent.TimeoutException;46import java.util.concurrent.locks.ReentrantLock;47/**48 * Manages the life and death of a native executable driver server.49 *50 * It is expected that the driver server implements the51 * <a href="https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol">WebDriver Wire Protocol</a>.52 * In particular, it should implement /status command that is used to check if the server is alive.53 * In addition to this, it is supposed that the driver server implements /shutdown hook that is54 * used to stop the server.55 */56public class DriverService implements Closeable {57 private static final String NAME = "Driver Service Executor";58 protected static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(20);59 private final ExecutorService executorService = Executors.newFixedThreadPool(2, r -> {60 Thread thread = new Thread(r);61 thread.setName(NAME);62 thread.setDaemon(true);63 return thread;64 });65 /**66 * The base URL for the managed server.67 */68 private final URL url;69 /**70 * Controls access to {@link #process}.71 */72 private final ReentrantLock lock = new ReentrantLock();73 private final String executable;74 private final Duration timeout;75 private final List<String> args;76 private final Map<String, String> environment;77 /**78 * A reference to the current child process. Will be {@code null} whenever this service is not79 * running. Protected by {@link #lock}.80 */81 protected CommandLine process = null;82 private OutputStream outputStream = System.err;83 /**84 *85 * @param executable The driver executable.86 * @param port Which port to start the driver server on.87 * @param timeout Timeout waiting for driver server to start.88 * @param args The arguments to the launched server.89 * @param environment The environment for the launched server.90 * @throws IOException If an I/O error occurs.91 */92 protected DriverService(93 File executable,94 int port,95 Duration timeout,96 List<String> args,97 Map<String, String> environment) throws IOException {98 this.executable = executable.getCanonicalPath();99 this.timeout = timeout;100 this.args = args;101 this.environment = environment;102 this.url = getUrl(port);103 }104 /**105 *106 * @param exeName Name of the executable file to look for in PATH107 * @param exeProperty Name of a system property that specifies the path to the executable file108 * @param exeDocs The link to the driver documentation page109 * @param exeDownload The link to the driver download page110 *111 * @return The driver executable as a {@link File} object112 * @throws IllegalStateException If the executable not found or cannot be executed113 */114 protected static File findExecutable(115 String exeName,116 String exeProperty,117 String exeDocs,118 String exeDownload) {119 String defaultPath = new ExecutableFinder().find(exeName);120 String exePath = System.getProperty(exeProperty, defaultPath);121 Require.state("The path to the driver executable", exePath).nonNull(122 "The path to the driver executable must be set by the %s system property;"123 + " for more information, see %s. "124 + "The latest version can be downloaded from %s",125 exeProperty, exeDocs, exeDownload);126 File exe = new File(exePath);127 checkExecutable(exe);128 return exe;129 }130 protected static void checkExecutable(File exe) {131 Require.state("The driver executable", exe).isFile();132 Require.stateCondition(exe.canExecute(), "It must be an executable file: %s", exe);133 }134 protected List<String> getArgs() {135 return args;136 }137 protected Map<String, String> getEnvironment() {138 return environment;139 }140 protected URL getUrl(int port) throws IOException {141 return new URL(String.format("http://localhost:%d", port));142 }143 /**144 * @return The base URL for the managed driver server.145 */146 public URL getUrl() {147 return url;148 }149 /**150 * Checks whether the driver child process is currently running.151 *152 * @return Whether the driver child process is still running.153 */154 public boolean isRunning() {155 lock.lock();156 try {157 return process != null && process.isRunning();158 } catch (IllegalThreadStateException e) {159 return true;160 } finally {161 lock.unlock();162 }163 }164 /**165 * Starts this service if it is not already running. This method will block until the server has166 * been fully started and is ready to handle commands.167 *168 * @throws IOException If an error occurs while spawning the child process.169 * @see #stop()170 */171 public void start() throws IOException {172 lock.lock();173 try {174 if (process != null) {175 return;176 }177 process = new CommandLine(this.executable, args.toArray(new String[] {}));178 process.setEnvironmentVariables(environment);179 process.copyOutputTo(getOutputStream());180 process.executeAsync();181 CompletableFuture<StartOrDie> serverStarted = CompletableFuture.supplyAsync(() -> {182 waitUntilAvailable();183 return StartOrDie.SERVER_STARTED;184 }, executorService);185 CompletableFuture<StartOrDie> processFinished = CompletableFuture.supplyAsync(() -> {186 try {187 process.waitFor(getTimeout().toMillis());188 } catch (org.openqa.selenium.TimeoutException ex) {189 return StartOrDie.PROCESS_IS_ACTIVE;190 }191 return StartOrDie.PROCESS_DIED;192 }, executorService);193 try {194 StartOrDie status = (StartOrDie) CompletableFuture.anyOf(serverStarted, processFinished)195 .get(getTimeout().toMillis() * 2, TimeUnit.MILLISECONDS);196 if (status == StartOrDie.SERVER_STARTED) {197 processFinished.cancel(true);198 } else {199 if (status == StartOrDie.PROCESS_DIED) {200 process = null;201 throw new WebDriverException("Driver server process died prematurely.");202 }203 }204 } catch (ExecutionException | TimeoutException e) {205 throw new WebDriverException("Timed out waiting for driver server to start.", e);206 } catch (InterruptedException e) {207 Thread.currentThread().interrupt();208 throw new WebDriverException("Timed out waiting for driver server to start.", e);209 }210 } finally {211 lock.unlock();212 }213 }214 protected Duration getTimeout() {215 return timeout;216 }217 protected void waitUntilAvailable() {218 try {219 URL status = new URL(url.toString() + "/status");220 new UrlChecker().waitUntilAvailable(getTimeout().toMillis(), TimeUnit.MILLISECONDS, status);221 } catch (MalformedURLException e) {222 throw new WebDriverException("Driver server status URL is malformed.", e);223 } catch (UrlChecker.TimeoutException e) {224 throw new WebDriverException("Timed out waiting for driver server to start.", e);225 }226 }227 /**228 * Stops this service if it is currently running. This method will attempt to block until the229 * server has been fully shutdown.230 *231 * @see #start()232 */233 public void stop() {234 lock.lock();235 WebDriverException toThrow = null;236 try {237 if (process == null) {238 return;239 }240 if (hasShutdownEndpoint()) {241 try {242 URL killUrl = new URL(url.toString() + "/shutdown");243 new UrlChecker().waitUntilUnavailable(3, SECONDS, killUrl);244 } catch (MalformedURLException e) {245 toThrow = new WebDriverException(e);246 } catch (UrlChecker.TimeoutException e) {247 toThrow = new WebDriverException("Timed out waiting for driver server to shutdown.", e);248 }249 }250 process.destroy();251 if (getOutputStream() instanceof FileOutputStream) {252 try {253 getOutputStream().close();254 } catch (IOException e) {255 }256 }257 } finally {258 process = null;259 lock.unlock();260 close();261 }262 if (toThrow != null) {263 throw toThrow;264 }265 }266 protected boolean hasShutdownEndpoint() {267 return true;268 }269 public void sendOutputTo(OutputStream outputStream) {270 this.outputStream = Require.nonNull("Output stream", outputStream);271 }272 protected OutputStream getOutputStream() {273 return outputStream;274 }275 @Override276 public void close() {277 shutdownGracefully(NAME, executorService);278 }279 private enum StartOrDie {280 SERVER_STARTED,281 PROCESS_IS_ACTIVE,282 PROCESS_DIED283 }284 public abstract static class Builder<DS extends DriverService, B extends Builder<?, ?>> {285 private int port = 0;286 private File exe = null;287 private Map<String, String> environment = emptyMap();288 private File logFile;289 private Duration timeout;290 /**291 * Provides a measure of how strongly this {@link DriverService} supports the given...

Full Screen

Full Screen

Source:DriverCommandExecutor.java Github

copy

Full Screen

...14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.remote.service;18import static org.openqa.selenium.concurrent.ExecutorServices.shutdownGracefully;19import com.google.common.annotations.VisibleForTesting;20import com.google.common.base.Throwables;21import org.openqa.selenium.WebDriverException;22import org.openqa.selenium.internal.Require;23import org.openqa.selenium.remote.Command;24import org.openqa.selenium.remote.CommandInfo;25import org.openqa.selenium.remote.DriverCommand;26import org.openqa.selenium.remote.HttpCommandExecutor;27import org.openqa.selenium.remote.Response;28import java.io.Closeable;29import java.io.IOException;30import java.net.ConnectException;31import java.util.Map;32import java.util.concurrent.CompletableFuture;33import java.util.concurrent.ExecutionException;34import java.util.concurrent.ExecutorService;35import java.util.concurrent.Executors;36import java.util.concurrent.TimeUnit;37import java.util.concurrent.TimeoutException;38/**39 * A specialized {@link HttpCommandExecutor} that will use a {@link DriverService} that lives40 * and dies with a single WebDriver session. The service will be restarted upon each new session41 * request and shutdown after each quit command.42 */43public class DriverCommandExecutor extends HttpCommandExecutor implements Closeable {44 private static final String NAME = "Driver Command Executor";45 private final DriverService service;46 private final ExecutorService executorService = Executors.newFixedThreadPool(2, r -> {47 Thread thread = new Thread(r);48 thread.setName(NAME);49 thread.setDaemon(true);50 return thread;51 });52 /**53 * Creates a new DriverCommandExecutor which will communicate with the driver as configured54 * by the given {@code service}.55 *56 * @param service The DriverService to send commands to.57 */58 public DriverCommandExecutor(DriverService service) {59 super(Require.nonNull("DriverService", service.getUrl()));60 this.service = service;61 }62 /**63 * Creates an {@link DriverCommandExecutor} that supports non-standard64 * {@code additionalCommands} in addition to the standard.65 *66 * @param service driver server67 * @param additionalCommands additional commands the remote end can process68 */69 protected DriverCommandExecutor(70 DriverService service, Map<String, CommandInfo> additionalCommands) {71 super(additionalCommands, service.getUrl());72 this.service = service;73 }74 /**75 * Sends the {@code command} to the driver server for execution. The server will be started76 * if requesting a new session. Likewise, if terminating a session, the server will be shutdown77 * once a response is received.78 *79 * @param command The command to execute.80 * @return The command response.81 * @throws IOException If an I/O error occurs while sending the command.82 */83 @Override84 public Response execute(Command command) throws IOException {85 boolean newlyStarted = false;86 if (DriverCommand.NEW_SESSION.equals(command.getName())) {87 boolean wasRunningBefore = service.isRunning();88 service.start();89 newlyStarted = !wasRunningBefore && service.isRunning();90 }91 if (DriverCommand.QUIT.equals(command.getName())) {92 CompletableFuture<Response> commandComplete = CompletableFuture.supplyAsync(() -> {93 try {94 return invokeExecute(command);95 } catch (Throwable t) {96 Throwable rootCause = Throwables.getRootCause(t);97 if (rootCause instanceof IllegalStateException98 && "Closed".equals(rootCause.getMessage())) {99 return null;100 }101 if (rootCause instanceof ConnectException102 && "Connection refused".equals(rootCause.getMessage())) {103 throw new WebDriverException("The driver server has unexpectedly died!", t);104 }105 Throwables.throwIfUnchecked(t);106 throw new WebDriverException(t);107 }108 }, executorService);109 CompletableFuture<Response> processFinished = CompletableFuture.supplyAsync(() -> {110 service.process.waitFor(service.getTimeout().toMillis());111 return null;112 }, executorService);113 try {114 Response response = (Response) CompletableFuture.anyOf(commandComplete, processFinished)115 .get(service.getTimeout().toMillis() * 2, TimeUnit.MILLISECONDS);116 service.stop();117 return response;118 } catch (ExecutionException | TimeoutException e) {119 throw new WebDriverException("Timed out waiting for driver server to stop.", e);120 } catch (InterruptedException e) {121 Thread.currentThread().interrupt();122 throw new WebDriverException("Timed out waiting for driver server to stop.", e);123 } finally {124 close();125 }126 } else {127 try {128 return invokeExecute(command);129 } catch (Throwable t) {130 Throwable rootCause = Throwables.getRootCause(t);131 if (rootCause instanceof ConnectException &&132 "Connection refused".equals(rootCause.getMessage()) &&133 !service.isRunning()) {134 throw new WebDriverException("The driver server has unexpectedly died!", t);135 }136 // an attempt to execute a command in the newly started driver server has failed137 // hence need to stop it138 if (newlyStarted && service.isRunning()) {139 try {140 service.stop();141 } catch (Exception ignored) {142 // fall through143 }144 }145 Throwables.throwIfUnchecked(t);146 throw new WebDriverException(t);147 }148 }149 }150 @VisibleForTesting151 Response invokeExecute(Command command) throws IOException {152 return super.execute(command);153 }154 @Override155 public void close() {156 shutdownGracefully(NAME, executorService);157 }158}...

Full Screen

Full Screen

Source:ExecutorServices.java Github

copy

Full Screen

...20import java.util.concurrent.ExecutorService;21import java.util.logging.Logger;22public class ExecutorServices {23 private static final Logger LOG = Logger.getLogger(ExecutorServices.class.getName());24 public static void shutdownGracefully(String name, ExecutorService service) {25 service.shutdown();26 try {27 if (!service.awaitTermination(5, SECONDS)) {28 LOG.warning(String.format("Failed to shutdown %s", name));29 service.shutdownNow();30 }31 } catch (InterruptedException e) {32 Thread.currentThread().interrupt();33 LOG.log(WARNING, String.format("Failed to shutdown %s", name), e);34 service.shutdownNow();35 }36 }37}...

Full Screen

Full Screen

shutdownGracefully

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.concurrent.ExecutorServices;2import org.openqa.selenium.net.PortProber;3import org.openqa.selenium.remote.server.SeleniumServer;4import org.openqa.selenium.remote.server.log.LoggingManager;5import org.openqa.selenium.remote.server.log.TerseFormatter;6import java.io.IOException;7import java.util.logging.Level;8import java.util.logging.Logger;9public class SeleniumServerShutdownDemo {10 private static final Logger LOG = LoggingManager.getLoggerForClass();11 public static void main(String[] args) throws IOException {12 LoggingManager.setLoggerLevel(Level.FINE);13 LoggingManager.setLoggerLevel(Level.FINE, TerseFormatter.class.getName());14 LoggingManager.setLoggerLevel(Level.FINE, SeleniumServer.class.getName());15 SeleniumServer server = new SeleniumServer(PortProber.findFreePort());16 server.boot();17 server.start();18 LOG.info("Server started");19 LOG.info("Shutdown server");20 ExecutorServices.getOrCreateDefaultExecutorService().shutdownGracefully();21 }22}

Full Screen

Full Screen

shutdownGracefully

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.concurrent.ExecutorServices;2import org.openqa.selenium.remote.service.DriverService;3public class DriverServiceShutdownGracefully {4 public static void main(String[] args) {5 DriverService service = null;6 try {7 service = new DriverService() {8 protected void start() {9 }10 protected void stop() {11 }12 };13 service.start();14 } finally {15 ExecutorServices.shutdownGracefully(service);16 }17 }18}19[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ selenium-java-examples ---20[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ selenium-java-examples ---21[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ selenium-java-examples ---22[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) @ selenium-java-examples ---23[INFO] --- maven-jar-plugin:3.1.2:jar (default-jar) @ selenium-java-examples ---

Full Screen

Full Screen

shutdownGracefully

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.concurrent.ExecutorServices;2import org.openqa.selenium.remote.RemoteWebDriver;3import org.openqa.selenium.remote.SessionId;4import org.openqa.selenium.remote.http.HttpClient;5import org.openqa.selenium.remote.http.HttpRequest;6import java.io.IOException;7public class ShutdownGracefully {8 public static void main(String[] args) throws IOException {9 SessionId sessionId = driver.getSessionId();10 HttpClient.Factory httpClientFactory = driver.getHttpClientFactory();11 HttpClient httpClient = httpClientFactory.createClient(driver.getCommandExecutor().getAddressOfRemoteServer());12 HttpRequest request = new HttpRequest(HttpMethod.POST, "/session/" + sessionId + "/shutdownGracefully");13 httpClient.execute(request);14 }15}16import org.openqa.selenium.remote.RemoteWebDriver;17public class ShutdownGracefully {18 public static void main(String[] args) {19 driver.shutdownGracefully();20 }21}22import org.openqa.selenium.remote.RemoteWebDriver;23import org.openqa.selenium.remote.SessionId;24import org.openqa.selenium.remote.http.HttpClient;25import org.openqa.selenium.remote.http.HttpRequest;26import java.io.IOException;27public class ShutdownGracefully {28 public static void main(String[] args) throws IOException {29 SessionId sessionId = driver.getSessionId();30 HttpClient httpClient = driver.getHttpClient();31 HttpRequest request = new HttpRequest(HttpMethod.POST, "/session/" + sessionId + "/shutdownGracefully");32 httpClient.execute(request);33 }34}35import org.openqa.selenium.remote.RemoteWebDriver;36import org.openqa.selenium.remote.SessionId;37import org.openqa.selenium.remote.http.HttpClient;38import org.openqa.selenium.remote.http.HttpRequest;39import java.io.IOException;40public class ShutdownGracefully {41 public static void main(String[] args) throws IOException {42 SessionId sessionId = driver.getSessionId();43 HttpClient httpClient = driver.getHttpClient();44 HttpRequest request = new HttpRequest(HttpMethod.POST, "/session/" +

Full Screen

Full Screen

shutdownGracefully

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.concurrent.ExecutorServices;2import org.openqa.selenium.remote.RemoteWebDriver;3import org.openqa.selenium.support.ui.WebDriverWait;4public class ExecutorServicesExample {5 public static void main(String[] args) {6 RemoteWebDriver driver = new RemoteWebDriver();7 ExecutorServices executorServices = new ExecutorServices(driver);8 executorServices.shutdownGracefully();9 }10}11Related Posts: How to use getExecutorService() method of the…12How to use shutdown() method of the ExecutorServices class?13How to use shutdownNow() method of the ExecutorServices class?14How to use shutdownGracefully() method of the…15How to use shutdownGracefully() method of the…16How to use shutdownGracefully() method of the…17How to use shutdownGracefully() method of the…18How to use shutdownGracefully() method of the…19How to use shutdownGracefully() method of the…20How to use shutdownGracefully() method of the…

Full Screen

Full Screen

shutdownGracefully

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.concurrent.ExecutorServices;2import org.openqa.selenium.remote.RemoteWebDriver;3import org.openqa.selenium.support.ui.WebDriverWait;4public class ExecutorServicesExample {5 public static void main(String[] args) {6 RemoteWebDriver driver = new RemoteWebDriver();7 ExecutorServices executorServices = new ExecutorServices(driver);8 executorServices.shutdownGracefully();9 }10}11Related Posts: How to use getExecutorService() method of the…12How to use shutdown() method of the ExecutorServices class?13How to use shutdownNow() method of the ExecutorServices class?14How to use shutdownGracefully() method of the…15How to use shutdownGracefully() method of the…16How to use shutdownGracefully() method of the…17How to use shutdownGracefully() method of the…18How to use shutdownGracefully() method of the…19How to use shutdownGracefully() method of the…20How to use shutdownGracefully() method of the…

Full Screen

Full Screen

shutdownGracefully

Using AI Code Generation

copy

Full Screen

1package com.example.selenium;2import org.openqa.selenium.concurrent.ExecutorServices;3import org.openqa.selenium.remote.DesiredCapabilities;4import org.openqa.selenium.remote.RemoteWebDriver;5import org.openqa.selenium.support.ui.WebDriverWait;6import org.openqa.selenium.support.ui.ExpectedConditions;7import org.openqa.selenium.By;8import org.openqa.selenium.WebElement;9import org.openqa.selenium.JavascriptExecutor;10import java.net.URL;11import java.util.concurrent.TimeUnit;12import java.util.concurrent.ExecutorService;13import java.util.concurrent.Executors;14import java.util.concurrent.TimeUnit;15import java.util.concurrent.ThreadFactory;16import java.util.concurrent.ThreadPoolExecutor;17import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;18import java.util.concurrent.atomic.AtomicInteger;19import java.util.concurrent.atomic.AtomicLong;20import java.util.concurrent.RejectedExecutionHandler;21import java.util.concurrent.CancellationException;22import java.util.concurrent.ExecutionException;23import java.util.concurrent.TimeoutException;24import java.util.concurrent.Callable;25import java.util.concurrent.Future;26import java.util.concurrent.ConcurrentHashMap;27import java.util.concurrent.ConcurrentMap;28import java.util.concurrent.atomic.AtomicBoolean;29import java.util.concurrent.atomic.AtomicInteger;30import java.util.concurrent.atomic.AtomicLong;31import java.util.concurrent.atomic.AtomicReference;32import java.util.concurrent.locks.ReentrantLock;33import java.util.concurrent.locks.Lock;34import java.util.concurrent.locks.ReentrantLock;35import java.util.concurrent.locks.Condition;36import java.util.concurrent.locks.ReentrantReadWriteLock;37import java.util.concurrent.locks.ReadWriteLock;38import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;39import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;40import java.util.concurrent.locks.LockSupport;41import java.util.concurrent.locks.AbstractQueuedSynchronizer;42import java.util.concurrent.locks.AbstractOwnableSynchronizer;43import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;44import java.util.concurrent.locks.AbstractOwnableSynchronizer;45import java.util.concurrent.locks.LockSupport;46import java.util.concurrent.locks.Condition;47import java.util.concurrent.locks.AbstractQueuedSynchronizer;48import java.util.concurrent.locks.AbstractOwnableSynchronizer;49import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;50import java.util.concurrent.locks.AbstractOwnableSynchronizer;51import java.util.concurrent.locks.LockSupport;52import java.util.concurrent.locks.Condition;53import java.util.concurrent.locks.AbstractQueuedSynchronizer;54import java.util.concurrent.locks.AbstractOwnableSynchronizer;55import java.util.concurrent.locks.AbstractQue

Full Screen

Full Screen

shutdownGracefully

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.concurrent.ExecutorServices;2ExecutorServices executorServices = new ExecutorServices();3executorServices.shutdownGracefully();4import org.openqa.selenium.concurrent.ExecutorServices;5ExecutorServices executorServices = new ExecutorServices();6executorServices.shutdownGracefully();7import org.openqa.selenium.concurrent.ExecutorServices;8ExecutorServices executorServices = new ExecutorServices();9executorServices.shutdownGracefully();10import org.openqa.selenium.concurrent.ExecutorServices;11ExecutorServices executorServices = new ExecutorServices();12executorServices.shutdownGracefully();13import org.openqa.selenium.concurrent.ExecutorServices;14ExecutorServices executorServices = new ExecutorServices();15executorServices.shutdownGracefully();16import org.openqa.selenium.concurrent.ExecutorServices;17ExecutorServices executorServices = new ExecutorServices();18executorServices.shutdownGracefully();19import org.openqa.selenium.concurrent.ExecutorServices;20import java.util.concurrent.ExecutorService;21import java.util.concurrent.Executors;22public class ShutdownExecutorService {23 public static void main(String args[]) {24 ExecutorService executorService = Executors.newSingleThreadExecutor();25 ExecutorServices.shutdownGracefully(executorService);26 }27}28[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ selenium-java-examples ---

Full Screen

Full Screen

shutdownGracefully

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.concurrent.ExecutorServices;2ExecutorServices executorServices = new ExecutorServices();3executorServices.shutdownGracefully();4import org.openqa.selenium.concurrent.ExecutorServices;5ExecutorServices executorServices = new ExecutorServices();6executorServices.shutdownGracefully();7import org.openqa.selenium.concurrent.ExecutorServices;8ExecutorServices executorServices = new ExecutorServices();9executorServices.shutdownGracefully();10import org.openqa.selenium.concurrent.ExecutorServices;11ExecutorServices executorServices = new ExecutorServices();12executorServices.shutdownGracefully();13import org.openqa.selenium.concurrent.ExecutorServices;14ExecutorServices executorServices = new ExecutorServices();15executorServices.shutdownGracefully();16import org.openqa.selenium.concurrent.ExecutorServices;17ExecutorServices executorServices = new ExecutorServices();18executorServices.shutdownGracefully();

Full Screen

Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in ExecutorServices

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful