How to use UrlChecker class of org.openqa.selenium.net package

Best Selenium code snippet using org.openqa.selenium.net.UrlChecker

Source:SeleniumGrid.java Github

copy

Full Screen

...57 private static final AtomicInteger THREAD_COUNTER = new AtomicInteger(1);58 private static final ExecutorService EXECUTOR = Executors.newCachedThreadPool(59 new ThreadFactory() {60 public Thread newThread(Runnable r) {61 Thread t = new Thread(r, "UrlChecker-" + THREAD_COUNTER.incrementAndGet()); // Thread safety reviewed62 t.setDaemon(true);63 return t;64 }65 });66 private GridServer hubServer;67 private Map<String, GridServer> nodeServers = new HashMap<>();68 protected Map<String, String> personalities = new HashMap<>();69 70 protected static final Logger LOGGER = LoggerFactory.getLogger(SeleniumGrid.class);71 72 /**73 * Constructor for Selenium Grid from hub URL.74 * <p>75 * This is used to create an interface for an active grid - remote or local.76 * 77 * @param config {@link SeleniumConfig} object78 * @param hubUrl {@link URL} for grid hub host79 * @throws IOException if unable to acquire Grid details80 */81 public SeleniumGrid(SeleniumConfig config, URL hubUrl) throws IOException {82 LOGGER.debug("Mapping structure of grid at: {}", hubUrl);83 hubServer = new GridServer(hubUrl, GridRole.HUB);84 for (String nodeEndpoint : GridUtility.getGridProxies(hubUrl)) {85 URL nodeUrl = new URL(nodeEndpoint + GridServer.HUB_BASE);86 nodeServers.put(nodeEndpoint, new GridServer(nodeUrl, GridRole.NODE));87 addNodePersonalities(config, hubServer.getUrl(), nodeEndpoint);88 }89 addPluginPersonalities(config);90 LOGGER.debug("{}: Personalities => {}", hubServer.getUrl(), personalities.keySet());91 }92 93 /**94 * Constructor for Selenium Grid from server objects.95 * <p>96 * This is used to create an interface for a newly-created local Grid.97 * 98 * @param config {@link SeleniumConfig} object99 * @param hubServer {@link GridServer} object for hub host100 * @param nodeServers array of {@link GridServer} objects for node hosts101 * @throws IOException if unable to acquire Grid details102 */103 public SeleniumGrid(SeleniumConfig config, GridServer hubServer, GridServer... nodeServers) throws IOException {104 this.hubServer = Objects.requireNonNull(hubServer);105 if (Objects.requireNonNull(nodeServers).length == 0) {106 throw new IllegalArgumentException("[nodeServers] must be non-empty");107 }108 LOGGER.debug("Assembling graph of grid at: {}", hubServer.getUrl());109 for (GridServer nodeServer : nodeServers) {110 String nodeEndpoint = "http://" + nodeServer.getUrl().getAuthority();111 this.nodeServers.put(nodeEndpoint, nodeServer);112 addNodePersonalities(config, hubServer.getUrl(), nodeEndpoint);113 }114 addPluginPersonalities(config);115 LOGGER.debug("{}: Personalities => {}", hubServer.getUrl(), personalities.keySet());116 }117 118 /**119 * Add supported personalities of the specified Grid node.120 * <p>121 * <b>NOTE</b>: Names of node personalities are derived from the following capabilities122 * (in order of precedence):123 * 124 * <ul>125 * <li><b>automationName</b>: 'appium' automation name</li>126 * <li><b>browserName</b>: name of target browser</li>127 * </ul>128 * 129 * @param config {@link SeleniumConfig} object130 * @param hubUrl {@link URL} of Grid hub131 * @param nodeEndpoint node endpoint132 * @throws IOException if an I/O error occurs133 */134 @SuppressWarnings({"unchecked", "rawtypes"})135 private void addNodePersonalities(SeleniumConfig config, URL hubUrl, String nodeEndpoint) throws IOException {136 LOGGER.debug("{}: Adding personalities of node: {}", hubUrl, nodeEndpoint);137 for (Capabilities capabilities : GridUtility.getNodeCapabilities(config, hubUrl, nodeEndpoint)) {138 Map<String, Object> req = (Map<String, Object>) capabilities.getCapability("request");139 List<Map> capsList = (List<Map>) req.get("capabilities");140 if (capsList == null) {141 Map<String, Object> conf = (Map<String, Object>) req.get("configuration");142 capsList = (List<Map>) conf.get("capabilities");143 }144 for (Map<String, Object> capsItem : capsList) {145 String browserName = (String) capsItem.get("automationName");146 if (browserName == null) {147 browserName = (String) capsItem.get("browserName");148 }149 personalities.putAll(PluginUtils.getPersonalitiesForBrowser(browserName));150 }151 }152 }153 154 /**155 * Add supported personalities from configured driver plug-ins.156 * 157 * @param config {@link SeleniumConfig} object158 */159 private void addPluginPersonalities(SeleniumConfig config) {160 for (DriverPlugin driverPlugin : LocalSeleniumGrid.getDriverPlugins(config)) {161 if (personalities.containsKey(driverPlugin.getBrowserName())) {162 personalities.putAll(driverPlugin.getPersonalities());163 }164 }165 }166 167 /**168 * Create an object that represents the Selenium Grid with the specified hub endpoint.169 * <p>170 * If the endpoint is {@code null} or specifies an inactive {@code localhost} URL, this method launches a local171 * Grid instance and returns a {@link LocalSeleniumGrid} object.172 * 173 * @param config {@link SeleniumConfig} object174 * @param hubUrl {@link URL} of hub host175 * @return {@link SeleniumGrid} object for the specified hub endpoint176 * @throws IOException if an I/O error occurs177 * @throws InterruptedException if this thread was interrupted178 * @throws TimeoutException if host timeout interval exceeded179 */180 public static SeleniumGrid create(SeleniumConfig config, URL hubUrl) throws IOException, InterruptedException, TimeoutException {181 if ((hubUrl != null) && GridUtility.isHubActive(hubUrl)) {182 // ensure that hub port is available as a discrete setting183 System.setProperty(SeleniumSettings.HUB_PORT.key(), Integer.toString(hubUrl.getPort()));184 return new SeleniumGrid(config, hubUrl);185 } else if ((hubUrl == null) || GridUtility.isLocalHost(hubUrl)) {186 return LocalSeleniumGrid.launch(config, config.createHubConfig());187 }188 throw new IllegalStateException("Specified remote hub URL '" + hubUrl + "' isn't active");189 }190 191 /**192 * Shutdown the Selenium Grid represented by this object.193 * 194 * @param localOnly {@code true} to target only local Grid servers195 * @return {@code false} if non-local Grid server encountered; otherwise {@code true}196 * @throws InterruptedException if this thread was interrupted197 */198 public boolean shutdown(final boolean localOnly) throws InterruptedException {199 boolean result = true;200 Iterator<Entry<String, GridServer>> iterator = nodeServers.entrySet().iterator();201 202 while (iterator.hasNext()) {203 Entry<String, GridServer> serverEntry = iterator.next();204 if (serverEntry.getValue().shutdown(localOnly)) {205 iterator.remove();206 } else {207 result = false;208 }209 }210 211 if (hubServer.shutdown(localOnly)) {212 hubServer = null;213 } else {214 result = false;215 }216 217 return result;218 }219 220 /**221 * Get grid server object for the active hub.222 * 223 * @return {@link GridServer} object that represents the active hub server224 */225 public GridServer getHubServer() {226 return hubServer;227 }228 229 /**230 * Get the map of grid server objects for the attached nodes.231 * 232 * @return map of {@link GridServer} objects that represent the attached node servers233 */234 public Map<String, GridServer> getNodeServers() {235 return nodeServers;236 }237 238 /**239 * Get capabilities object for the specified browser personality.240 * 241 * @param config {@link SeleniumConfig} object242 * @param personality browser personality to retrieve243 * @return {@link Capabilities} object for the specified personality244 * @throws IllegalArgumentException if specified personality isn't supported by the active Grid245 */246 public Capabilities getPersonality(SeleniumConfig config, String personality) {247 String json = personalities.get(personality);248 if ((json == null) || json.isEmpty()) {249 String message = String.format("Specified personality '%s' not supported by active Grid", personality);250 String browserName = personality.split("\\.")[0];251 if ( ! browserName.equals(personality)) {252 LOGGER.warn("{}; revert to browser name '{}'", message, browserName);253 Capabilities[] capsList = config.getCapabilitiesForName(browserName);254 if (capsList.length > 0) {255 return capsList[0];256 }257 }258 throw new IllegalArgumentException(message);259 } else {260 return config.getCapabilitiesForJson(json)[0];261 }262 }263 /**264 * This class represents a single Selenium Grid server (hub or node).265 */266 public static class GridServer {267 private GridRole role;268 private URL serverUrl;269 protected String statusRequest;270 protected String shutdownRequest;271 272 public static final String GRID_CONSOLE = "/grid/console";273 public static final String HUB_BASE = "/wd/hub";274 public static final String NODE_STATUS = "/wd/hub/status";275 public static final String HUB_CONFIG = "/grid/api/hub/";276 public static final String NODE_CONFIG = "/grid/api/proxy";277 278 private static final String HUB_SHUTDOWN = "/lifecycle-manager?action=shutdown";279 private static final String NODE_SHUTDOWN = "/extra/LifecycleServlet?action=shutdown";280 private static final long SHUTDOWN_DELAY = 15;281 282 public GridServer(URL url, GridRole role) {283 this.role = role;284 this.serverUrl = url;285 if (isHub()) {286 statusRequest = HUB_CONFIG;287 shutdownRequest = HUB_SHUTDOWN;288 } else {289 statusRequest = NODE_STATUS;290 shutdownRequest = NODE_SHUTDOWN;291 }292 }293 294 /**295 * Determine if this Grid server is a hub host.296 * 297 * @return {@code true} if this server is a hub; otherwise {@code false}298 */299 public boolean isHub() {300 return (role == GridRole.HUB);301 }302 303 /**304 * Get the URL for this server.305 * 306 * @return {@link URL} object for this server307 */308 public URL getUrl() {309 return serverUrl;310 }311 312 public boolean isActive() {313 return GridUtility.isHostActive(serverUrl, statusRequest);314 }315 316 /**317 * Stop the Selenium Grid server represented by this object.318 * 319 * @param localOnly {@code true} to target only local Grid server320 * @return {@code false} if [localOnly] and server is remote; otherwise {@code true}321 * @throws InterruptedException if this thread was interrupted322 */323 public boolean shutdown(final boolean localOnly) throws InterruptedException {324 return shutdown(this, shutdownRequest, localOnly);325 }326 /**327 * Stop the specified Selenium Grid server.328 * 329 * @param gridServer {@link GridServer} object for hub or node330 * @param shutdownRequest Selenium server shutdown request331 * @param localOnly {@code true} to target only local Grid server332 * @return {@code false} if [localOnly] and server is remote; otherwise {@code true}333 * @throws InterruptedException if this thread was interrupted334 */335 public static boolean shutdown(final GridServer gridServer, final String shutdownRequest,336 final boolean localOnly) throws InterruptedException {337 338 URL serverUrl = gridServer.getUrl();339 340 if (localOnly && !GridUtility.isLocalHost(serverUrl)) {341 return false;342 }343 344 if (gridServer.isActive()) {345 if ( ! gridServer.isHub() && (gridServer instanceof LocalGridServer)) {346 ((LocalGridServer) gridServer).getProcess().destroy();347 } else {348 try {349 GridUtility.getHttpResponse(serverUrl, shutdownRequest);350 waitUntilUnavailable(SHUTDOWN_DELAY, TimeUnit.SECONDS, serverUrl);351 } catch (IOException | org.openqa.selenium.net.UrlChecker.TimeoutException e) {352 throw UncheckedThrow.throwUnchecked(e);353 }354 }355 }356 357 Thread.sleep(1000);358 return true;359 }360 }361 /**362 * Wait up to the specified interval for the indicated URL(s) to be available.363 * <p>364 * <b>NOTE</b>: This method was back-ported from the {@link org.openqa.selenium.net.UrlChecker UrlChecker} class in365 * Selenium 3 to compile under Java 7.366 * 367 * @param timeout timeout interval368 * @param unit granularity of specified timeout369 * @param urls URLs to poll for availability370 * @throws org.openqa.selenium.net.UrlChecker.TimeoutException if indicated URL is still available after specified371 * interval.372 */373 public static void waitUntilAvailable(long timeout, TimeUnit unit, final URL... urls)374 throws org.openqa.selenium.net.UrlChecker.TimeoutException {375 long start = System.nanoTime();376 try {377 Future<Void> callback = EXECUTOR.submit(new Callable<Void>() {378 public Void call() throws InterruptedException {379 HttpURLConnection connection = null;380 long sleepMillis = MIN_POLL_INTERVAL_MS;381 while (true) {382 if (Thread.interrupted()) {383 throw new InterruptedException();384 }385 for (URL url : urls) {386 try {387 connection = connectToUrl(url);388 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {389 return null;390 }391 } catch (IOException e) {392 // Ok, try again.393 } finally {394 if (connection != null) {395 connection.disconnect();396 }397 }398 }399 MILLISECONDS.sleep(sleepMillis);400 sleepMillis = (sleepMillis >= MAX_POLL_INTERVAL_MS) ? sleepMillis : sleepMillis * 2;401 }402 }403 });404 callback.get(timeout, unit);405 } catch (java.util.concurrent.TimeoutException e) {406 throw new org.openqa.selenium.net.UrlChecker.TimeoutException(407 String.format("Timed out waiting for %s to be available after %d ms", Arrays.toString(urls),408 MILLISECONDS.convert(System.nanoTime() - start, NANOSECONDS)),409 e);410 } catch (InterruptedException e) {411 Thread.currentThread().interrupt();412 throw new RuntimeException(e);413 } catch (ExecutionException e) {414 throw new RuntimeException(e);415 }416 }417 /**418 * Wait up to the specified interval for the indicated URL to be unavailable.419 * <p>420 * <b>NOTE</b>: This method was back-ported from the {@link org.openqa.selenium.net.UrlChecker UrlChecker} class in421 * Selenium 3 to compile under Java 7.422 * 423 * @param timeout timeout interval424 * @param unit granularity of specified timeout425 * @param url URL to poll for availability426 * @throws org.openqa.selenium.net.UrlChecker.TimeoutException if indicated URL is still available after specified427 * interval.428 */429 public static void waitUntilUnavailable(long timeout, TimeUnit unit, final URL url)430 throws org.openqa.selenium.net.UrlChecker.TimeoutException {431 long start = System.nanoTime();432 try {433 Future<Void> callback = EXECUTOR.submit(new Callable<Void>() {434 public Void call() throws InterruptedException {435 HttpURLConnection connection = null;436 long sleepMillis = MIN_POLL_INTERVAL_MS;437 while (true) {438 try {439 connection = connectToUrl(url);440 if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {441 return null;442 }443 } catch (IOException e) {444 return null;445 } finally {446 if (connection != null) {447 connection.disconnect();448 }449 }450 MILLISECONDS.sleep(sleepMillis);451 sleepMillis = (sleepMillis >= MAX_POLL_INTERVAL_MS) ? sleepMillis452 : sleepMillis * 2;453 }454 }455 });456 callback.get(timeout, unit);457 } catch (TimeoutException e) {458 throw new org.openqa.selenium.net.UrlChecker.TimeoutException(String.format(459 "Timed out waiting for %s to become unavailable after %d ms", url,460 MILLISECONDS.convert(System.nanoTime() - start, NANOSECONDS)), e);461 } catch (RuntimeException e) {462 throw e;463 } catch (Exception e) {464 throw new RuntimeException(e);465 }466 }467 /**468 * Create a connection to the specified URL.469 * <p>470 * <b>NOTE</b>: This method was lifted from the {@link org.openqa.selenium.net.UrlChecker UrlChecker} class in the471 * Selenium API.472 * 473 * @param url URL for connection474 * @return connection to the specified URL475 * @throws IOException if an I/O exception occurs476 */477 private static HttpURLConnection connectToUrl(URL url) throws IOException {478 HttpURLConnection connection = (HttpURLConnection) url.openConnection();479 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);480 connection.setReadTimeout(READ_TIMEOUT_MS);481 connection.connect();482 return connection;483 }484}...

Full Screen

Full Screen

Source:DriverService.java Github

copy

Full Screen

...12import java.util.concurrent.locks.ReentrantLock;13import org.openqa.selenium.Beta;14import org.openqa.selenium.WebDriverException;15import org.openqa.selenium.net.PortProber;16import org.openqa.selenium.net.UrlChecker;17import org.openqa.selenium.net.UrlChecker.TimeoutException;18import org.openqa.selenium.os.CommandLine;19import org.openqa.selenium.os.ExecutableFinder;20public class DriverService21{22 private final URL url;23 private final ReentrantLock lock = new ReentrantLock();24 25 private CommandLine process = null;26 27 private final String executable;28 private final ImmutableList<String> args;29 private final ImmutableMap<String, String> environment;30 private OutputStream outputStream = System.err;31 32 protected DriverService(File executable, int port, ImmutableList<String> args, ImmutableMap<String, String> environment)33 throws IOException34 {35 this.executable = executable.getCanonicalPath();36 this.args = args;37 this.environment = environment;38 39 url = getUrl(port);40 }41 42 protected URL getUrl(int port) throws IOException {43 return new URL(String.format("http://localhost:%d", new Object[] { Integer.valueOf(port) }));44 }45 46 public URL getUrl()47 {48 return url;49 }50 51 protected static File findExecutable(String exeName, String exeProperty, String exeDocs, String exeDownload)52 {53 String defaultPath = new ExecutableFinder().find(exeName);54 String exePath = System.getProperty(exeProperty, defaultPath);55 Preconditions.checkState(exePath != null, "The path to the driver executable must be set by the %s system property; for more information, see %s. The latest version can be downloaded from %s", exeProperty, exeDocs, exeDownload);56 57 File exe = new File(exePath);58 checkExecutable(exe);59 return exe;60 }61 62 protected static void checkExecutable(File exe) {63 Preconditions.checkState(exe.exists(), "The driver executable does not exist: %s", exe64 .getAbsolutePath());65 Preconditions.checkState(!exe.isDirectory(), "The driver executable is a directory: %s", exe66 .getAbsolutePath());67 Preconditions.checkState(exe.canExecute(), "The driver is not executable: %s", exe68 .getAbsolutePath());69 }70 71 public boolean isRunning()72 {73 lock.lock();74 try { boolean bool1;75 if (process == null) {76 return false;77 }78 return process.isRunning();79 } catch (IllegalThreadStateException e) {80 return true;81 } finally {82 lock.unlock();83 }84 }85 86 public void start()87 throws IOException88 {89 lock.lock();90 try {91 if (process != null) {92 return;93 }94 process = new CommandLine(executable, (String[])args.toArray(new String[0]));95 process.setEnvironmentVariables(environment);96 process.copyOutputTo(getOutputStream());97 process.executeAsync();98 99 waitUntilAvailable();100 } finally {101 lock.unlock();102 }103 }104 105 protected void waitUntilAvailable() throws MalformedURLException {106 try {107 URL status = new URL(url.toString() + "/status");108 new UrlChecker().waitUntilAvailable(20L, TimeUnit.SECONDS, new URL[] { status });109 } catch (UrlChecker.TimeoutException e) {110 process.checkForError();111 throw new WebDriverException("Timed out waiting for driver server to start.", e);112 }113 }114 115 public void stop()116 {117 lock.lock();118 119 WebDriverException toThrow = null;120 try {121 if (process == null) {122 return;123 }124 try125 {126 URL killUrl = new URL(url.toString() + "/shutdown");127 new UrlChecker().waitUntilUnavailable(3L, TimeUnit.SECONDS, killUrl);128 } catch (MalformedURLException e) {129 toThrow = new WebDriverException(e);130 } catch (UrlChecker.TimeoutException e) {131 toThrow = new WebDriverException("Timed out waiting for driver server to shutdown.", e);132 }133 134 process.destroy();135 } finally {136 process = null;137 lock.unlock();138 }139 140 if (toThrow != null) {141 throw toThrow;142 }143 }144 ...

Full Screen

Full Screen

Source:OutOfProcessSeleniumServer.java Github

copy

Full Screen

...18import static java.util.concurrent.TimeUnit.SECONDS;19import org.openqa.selenium.BuckBuild;20import org.openqa.selenium.net.NetworkUtils;21import org.openqa.selenium.net.PortProber;22import org.openqa.selenium.net.UrlChecker;23import org.openqa.selenium.os.CommandLine;24import org.openqa.selenium.testing.InProject;25import java.io.IOException;26import java.net.MalformedURLException;27import java.net.URL;28import java.nio.file.Path;29import java.util.Arrays;30import java.util.LinkedList;31import java.util.List;32import java.util.logging.Logger;33public class OutOfProcessSeleniumServer {34 private static final Logger log = Logger.getLogger(OutOfProcessSeleniumServer.class.getName());35 private String baseUrl;36 private CommandLine command;37 @SuppressWarnings("unused")38 private boolean captureLogs = false;39 public void enableLogCapture() {40 captureLogs = true;41 }42 /**43 * Creates an out of process server with log capture enabled.44 *45 * @return The new server.46 */47 public OutOfProcessSeleniumServer start(String... extraFlags) throws IOException {48 log.info("Got a request to start a new selenium server");49 if (command != null) {50 log.info("Server already started");51 throw new RuntimeException("Server already started");52 }53 String serverJar = buildServerAndClasspath();54 int port = PortProber.findFreePort();55 String localAddress = new NetworkUtils().getPrivateLocalAddress();56 baseUrl = String.format("http://%s:%d", localAddress, port);57 List<String> cmdLine = new LinkedList<>();58 cmdLine.add("java");59 cmdLine.add("-jar");60 cmdLine.add(serverJar);61 cmdLine.add("-port");62 cmdLine.add(String.valueOf(port));63 cmdLine.addAll(Arrays.asList(extraFlags));64 command = new CommandLine(cmdLine.toArray(new String[cmdLine.size()]));65 if (Boolean.getBoolean("webdriver.development")) {66 command.copyOutputTo(System.err);67 }68 command.setWorkingDirectory(69 InProject.locate("Rakefile").getParent().toAbsolutePath().toString());70 log.info("Starting selenium server: " + command.toString());71 command.executeAsync();72 try {73 URL url = new URL(baseUrl + "/wd/hub/status");74 log.info("Waiting for server status on URL " + url);75 new UrlChecker().waitUntilAvailable(30, SECONDS, url);76 log.info("Server is ready");77 } catch (UrlChecker.TimeoutException e) {78 log.severe("Server failed to start: " + e.getMessage());79 command.destroy();80 log.severe(command.getStdOut());81 command = null;82 throw new RuntimeException(e);83 } catch (MalformedURLException e) {84 throw new RuntimeException(e);85 }86 return this;87 }88 public void stop() {89 if (command == null) {90 return;91 }...

Full Screen

Full Screen

Source:UrlCheckerTest.java Github

copy

Full Screen

...31import java.util.concurrent.TimeUnit;32import javax.servlet.ServletException;33import javax.servlet.http.HttpServletRequest;34import javax.servlet.http.HttpServletResponse;35public class UrlCheckerTest {36 private final UrlChecker urlChecker = new UrlChecker();37 int port = findFreePort();38 Server server = buildServer();39 private Server buildServer() {40 Server server = new Server(port);41 server.setHandler(new AbstractHandler() {42 @Override43 public void handle(String s, Request request, HttpServletRequest httpServletRequest,44 HttpServletResponse httpServletResponse)45 throws IOException, ServletException {46 httpServletResponse.setStatus(200);47 httpServletResponse.getWriter().println("<h1>Working</h1>");48 request.setHandled(true);49 }50 });51 return server;52 }53 ExecutorService executorService = Executors.newSingleThreadExecutor();54 @Test55 public void testWaitUntilAvailableIsTimely() throws Exception {56 long delay = 200L;57 executorService.submit(() -> {58 Thread.sleep(delay);59 server.start();60 return null;61 });62 long start = currentTimeMillis();63 urlChecker.waitUntilAvailable(10, TimeUnit.SECONDS, new URL("http://localhost:" + port + "/"));64 long elapsed = currentTimeMillis() - start;65 assertThat(elapsed, lessThan(UrlChecker.CONNECT_TIMEOUT_MS + 100L)); // threshold66 }67 @Test68 public void testWaitUntilUnavailableIsTimely() throws Exception {69 long delay = 200L;70 server.start();71 urlChecker.waitUntilAvailable(10, TimeUnit.SECONDS, new URL("http://localhost:" + port + "/"));72 executorService.submit(() -> {73 Thread.sleep(delay);74 server.stop();75 return null;76 });77 long start = currentTimeMillis();78 urlChecker.waitUntilUnavailable(10, TimeUnit.SECONDS, new URL("http://localhost:" + port + "/"));79 long elapsed = currentTimeMillis() - start;80 assertThat(elapsed, lessThan(UrlChecker.CONNECT_TIMEOUT_MS + delay + 200L)); // threshold81 System.out.println(elapsed);82 }83 @After84 public void cleanup() throws Exception {85 server.stop();86 server.join();87 executorService.shutdown();88 }89}...

Full Screen

Full Screen

Source:GridViaCommandLineTest.java Github

copy

Full Screen

...21import org.openqa.selenium.By;22import org.openqa.selenium.WebDriver;23import org.openqa.selenium.io.IOUtils;24import org.openqa.selenium.net.PortProber;25import org.openqa.selenium.net.UrlChecker;26import org.openqa.selenium.remote.DesiredCapabilities;27import org.openqa.selenium.remote.RemoteWebDriver;28import org.openqa.selenium.support.ui.FluentWait;29import java.io.IOException;30import java.net.URL;31import java.net.URLConnection;32import java.util.concurrent.TimeUnit;33/**34 * Ensure that launching the hub / node in most common ways simulating command line args works35 */36public class GridViaCommandLineTest {37 @Test38 public void testRegisterNodeToHub() throws Exception {39 Integer hubPort = PortProber.findFreePort();40 String[] hubArgs = {"-role", "hub", "-port", hubPort.toString()};41 GridLauncherV3.main(hubArgs);42 UrlChecker urlChecker = new UrlChecker();43 urlChecker.waitUntilAvailable(10, TimeUnit.SECONDS, new URL(String.format("http://localhost:%d/grid/console", hubPort)));44 Integer nodePort = PortProber.findFreePort();45 String[] nodeArgs = {"-role", "node", "-hub", "http://localhost:" + hubPort, "-browser", "browserName=chrome,maxInstances=1", "-port", nodePort.toString()};46 GridLauncherV3.main(nodeArgs);47 urlChecker.waitUntilAvailable(100, TimeUnit.SECONDS, new URL(String.format("http://localhost:%d/wd/hub/status", nodePort)));48 new FluentWait<URL>(new URL(String.format("http://localhost:%d/grid/console", hubPort))).withTimeout(5, TimeUnit.SECONDS).pollingEvery(50, TimeUnit.MILLISECONDS)49 .until((URL u) -> {50 try {51 return IOUtils.readFully(u.openConnection().getInputStream()).contains("chrome");52 } catch (IOException ioe) {53 return false;54 }55 });56 WebDriver driver = new RemoteWebDriver(new URL(String.format("http://localhost:%d/wd/hub", hubPort)),...

Full Screen

Full Screen

UrlChecker

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.net.UrlChecker;2import org.openqa.selenium.net.UrlChecker.TimeoutException;3import java.net.URL;4import java.util.concurrent.TimeUnit;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.chrome.ChromeDriver;7public class UrlCheckerExample {8 public static void main(String[] args) throws Exception {9 WebDriver driver = new ChromeDriver();10 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);11 String url = driver.getCurrentUrl();12 UrlChecker urlChecker = new UrlChecker();13 try {14 urlChecker.waitUntilAvailable(60, TimeUnit.SECONDS, new URL(url));15 System.out.println("URL is available");16 } catch (TimeoutException e) {17 System.out.println("URL is not available");18 }19 driver.quit();20 }21}22import java.net.URL;23public class ValidUrlExample {24 public static void main(String[] args) throws Exception {25 try {26 new URL(url).toURI();27 System.out.println("Valid URL");28 } catch (Exception e) {29 System.out.println("Invalid URL");30 }31 }32}33import java.net.HttpURLConnection;34import java.net.URL;35public class BrokenUrlExample {36 public static void main(String[] args) throws Exception {37 HttpURLConnection huc = (HttpURLConnection)(new URL(url).openConnection());38 huc.setRequestMethod("HEAD");

Full Screen

Full Screen

UrlChecker

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.net.UrlChecker;2import java.net.URL;3import java.util.concurrent.TimeUnit;4import java.net.MalformedURLException;5import java.net.URL;6import java.net.URLConnection;7import java.net.HttpURLConnection;8import org.openqa.selenium.net.UrlChecker.TimeoutException;9import org.openqa.selenium.net.UrlChecker.UnreachableBrowserException;10import org.openqa.selenium.net.UrlChecker.UnexpectedPageContentException;11public class UrlChecker {12 public static void main(String[] args) {13 try {14 UrlChecker urlChecker = new UrlChecker();15 urlChecker.waitUntilAvailable(30, TimeUnit.SECONDS, new URL(url));16 System.out.println("Page is available");17 } catch (TimeoutException e) {18 System.out.println("Page is not available");19 } catch (MalformedURLException e) {20 System.out.println("Invalid URL");21 }22 }23}24import org.openqa.selenium.support.ui.UrlChecker;25import java.net.URL;26import java.util.concurrent.TimeUnit;27import java.net.MalformedURLException;28import java.net.URL;29import java.net.URLConnection;30import java.net.HttpURLConnection;31import org.openqa.selenium.support.ui.UrlChecker.TimeoutException;32import org.openqa.selenium.support.ui.UrlChecker.UnreachableBrowserException;33import org.openqa.selenium.support.ui.UrlChecker.UnexpectedPageContentException;34public class UrlChecker {35 public static void main(String[] args) {36 try {37 UrlChecker urlChecker = new UrlChecker();38 urlChecker.waitUntilAvailable(30, TimeUnit.SECONDS, new URL(url));39 System.out.println("Page is available");40 } catch (TimeoutException e) {41 System.out.println("Page is not available");42 } catch (MalformedURLException e) {43 System.out.println("Invalid URL");44 }45 }46}47import org.openqa.selenium.support.UrlChecker;48import java.net.URL;49import java.util.concurrent.TimeUnit;50import java.net.MalformedURLException;51import java.net.URL;52import java.net.URLConnection;53import java.net.HttpURLConnection;54import org.openqa.selenium.support.UrlChecker.TimeoutException;55import org.openqa.selenium.support.UrlChecker.UnreachableBrowserException;56import org.openqa.selenium.support.UrlChecker.UnexpectedPageContentException;57public class UrlChecker {58 public static void main(String[] args) {

Full Screen

Full Screen

UrlChecker

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.net.UrlChecker;2import org.openqa.selenium.net.UrlChecker.TimeoutException;3import java.net.URL;4public class UrlCheckerExample {5 public static void main(String[] args) throws Exception {6 long timeout = 5000;7 try {8 new UrlChecker().waitUntilAvailable(timeout, url);9 } catch (TimeoutException e) {10 System.out.println("The url was not available");11 }12 }13}

Full Screen

Full Screen

UrlChecker

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.net.UrlChecker;2import java.net.URL;3import java.util.concurrent.TimeUnit;4import java.util.concurrent.TimeoutException;5public class CheckUrl {6 public static void main(String[] args) throws TimeoutException {7 UrlChecker urlChecker = new UrlChecker();8 URL url = null;9 try {10 } catch (Exception e) {11 e.printStackTrace();12 }13 urlChecker.waitUntilAvailable(5, TimeUnit.SECONDS, url);14 System.out.println("The url is available");15 }16}

Full Screen

Full Screen

UrlChecker

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.net.UrlChecker;2import org.openqa.selenium.net.UrlChecker.TimeoutException;3import java.net.URL;4import java.util.concurrent.TimeUnit;5public class CheckURL {6 public static void main(String[] args) {7 try {8 UrlChecker urlChecker = new UrlChecker();9 System.out.println("URL is reachable");10 } catch (TimeoutException e) {11 System.out.println("URL is not reachable");12 } catch (Exception e) {13 System.out.println("Exception occured");14 }15 }16}

Full Screen

Full Screen
copy
1User target = userRepository.findById(id1).orElse(null);2User source = userRepository.findById(id2).orElse(null);3Event event = eventRepository.findById(id3).orElse(null);45if (target != null && source != null && event != null) {6 String message = String.format("Hi %s, %s has invited you to %s",7 target.getName(), source.getName(), event.getName());8 sendInvite(target.getEmail(), message);9}10
Full Screen
copy
1return userRepository.findById(id)2 .flatMap(target -> userRepository.findById(id2)3 .map(User::getName)4 .flatMap(sourceName -> eventRepository.findById(id3)5 .map(Event::getName)6 .map(eventName-> createInvite(target, sourceName, eventName))))7
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 methods in UrlChecker

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful