diff --git a/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java b/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java
index 20ac611a9..805a4be9d 100644
--- a/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java
+++ b/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java
@@ -18,8 +18,10 @@
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
+import io.appium.java_client.AppiumClientConfig;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.options.UiAutomator2Options;
+import io.appium.java_client.remote.AppiumCommandExecutor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -37,6 +39,7 @@
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
+import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
@@ -261,4 +264,25 @@ void failsToProvideBiDiWithoutTheWebSocketUrlCapability() throws IOException {
assertThrows(BiDiException.class, seleniumDriver::getHandle);
}
+
+ @Test
+ void propagatesDirectConnectServerUrlToSeleniumClientConfig() throws IOException {
+ extraCapabilities = "\"appium:directConnectProtocol\":\"https\","
+ + "\"appium:directConnectHost\":\"203.0.113.1\","
+ + "\"appium:directConnectPort\":4443,"
+ + "\"appium:directConnectPath\":\"/wd/hub\",";
+ var clientConfig = AppiumClientConfig.defaultConfig()
+ .baseUri(URI.create("http://127.0.0.1:" + server.getAddress().getPort()))
+ .directConnect(true);
+ var appiumDriver = new AndroidDriver(clientConfig,
+ new UiAutomator2Options().setDeviceName("Android Emulator"));
+ var seleniumDriver = SeleniumBridge.asRemoteWebDriver(appiumDriver);
+ try {
+ assertEquals(URI.create("https://203.0.113.1:4443/wd/hub"),
+ seleniumDriver.getClientConfig().baseUri());
+ } finally {
+ seleniumDriver.closeBiDi();
+ ((AppiumCommandExecutor) appiumDriver.getCommandExecutor()).close();
+ }
+ }
}
diff --git a/src/main/java/io/appium/java_client/AppiumDriver.java b/src/main/java/io/appium/java_client/AppiumDriver.java
index ccdfffd13..c471fbf50 100644
--- a/src/main/java/io/appium/java_client/AppiumDriver.java
+++ b/src/main/java/io/appium/java_client/AppiumDriver.java
@@ -31,7 +31,7 @@
import io.appium.java_client.remote.options.BaseOptions;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
-import lombok.Getter;
+import org.jspecify.annotations.Nullable;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.OutputType;
@@ -64,8 +64,6 @@ public class AppiumDriver extends AppiumRemoteWebDriver implements
private static final ErrorHandler ERROR_HANDLER = new ErrorHandler(new ErrorCodesMobile());
// frequently used command parameters
- @Getter
- private final URL remoteAddress;
private final ExecuteMethod executeMethod;
/**
@@ -80,7 +78,6 @@ public AppiumDriver(AppiumCommandExecutor executor, Capabilities capabilities) {
super(executor, capabilities);
this.executeMethod = new AppiumExecutionMethod(this);
super.setErrorHandler(ERROR_HANDLER);
- this.remoteAddress = executor.getAddressOfRemoteServer();
}
/**
@@ -216,11 +213,20 @@ public AppiumDriver(URL remoteSessionAddress, String platformName, String automa
setCommandExecutor(executor);
this.executeMethod = new AppiumExecutionMethod(this);
super.setErrorHandler(ERROR_HANDLER);
- this.remoteAddress = executor.getAddressOfRemoteServer();
setSessionId(sessionAddress.getId());
}
+ /**
+ * Gets the remote server address to which commands are sent.
+ *
+ * @return the remote server URL, or {@code null} if not configured
+ */
+ @Nullable
+ public URL getRemoteAddress() {
+ return ((AppiumCommandExecutor) getCommandExecutor()).getAddressOfRemoteServer();
+ }
+
@Override
public ExecuteMethod getExecuteMethod() {
return executeMethod;
diff --git a/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java b/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java
index 6b0b27759..ca6eb63c1 100644
--- a/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java
+++ b/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java
@@ -18,17 +18,12 @@
import io.appium.java_client.CommandExecutionHelper;
import io.appium.java_client.ExecutesMethod;
-import io.appium.java_client.remote.AppiumCommandExecutor;
-import io.appium.java_client.remote.AppiumRemoteWebDriver;
+import io.appium.java_client.internal.LogBroadcastEndpoints;
import io.appium.java_client.ws.StringWebSocketClient;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
import java.util.function.Consumer;
import static io.appium.java_client.service.local.AppiumServiceBuilder.DEFAULT_APPIUM_PORT;
-import static java.util.Objects.requireNonNull;
/**
* Provides listening to logcat messages broadcast via web socket.
@@ -60,14 +55,14 @@ public interface ListensToLogcatMessages extends ExecutesMethod {
*/
@Deprecated(since = "11.1.0", forRemoval = true)
default void startLogcatBroadcast() {
- URL serverUrl = getRemoteServerUrl();
- startLogcatBroadcast(serverUrl.getHost(), serverUrl.getPort());
+ LogBroadcastEndpoints.startBroadcast(this, this::getLogcatClient, "logcat");
}
/**
* Start logcat messages broadcast via web socket.
* This method assumes that Appium server is assigned to the default port (4723).
- * The scheme still follows the server this driver is connected to.
+ * The scheme follows the initial Appium server URL configured on the executor,
+ * defaulting to {@code ws} if unset.
*
* @param host the name of the host where Appium server is running
*/
@@ -78,7 +73,8 @@ default void startLogcatBroadcast(String host) {
/**
* Start logcat messages broadcast via web socket.
- * The scheme follows the server this driver is connected to.
+ * The scheme follows the initial Appium server URL configured on the executor,
+ * defaulting to {@code ws} if unset.
* The socket path is the server-root logcat route; an HTTP base path is not added.
*
* @param host the name of the host where Appium server is running
@@ -87,48 +83,7 @@ default void startLogcatBroadcast(String host) {
*/
@Deprecated(since = "11.1.0", forRemoval = true)
default void startLogcatBroadcast(String host, int port) {
- var remoteWebDriver = (AppiumRemoteWebDriver) this;
- URI endpoint = buildLogcatEndpoint(getRemoteServerUrl(), host, port,
- String.valueOf(remoteWebDriver.getSessionId()));
- CommandExecutionHelper.executeScript(this, "mobile: startLogsBroadcast");
- getLogcatClient().connect(endpoint);
- }
-
- /**
- * Returns the Appium server URL commands are sent to.
- *
- * @return the remote server URL
- */
- private URL getRemoteServerUrl() {
- var remoteWebDriver = (AppiumRemoteWebDriver) this;
- URL serverUrl = ((AppiumCommandExecutor) remoteWebDriver.getCommandExecutor()).getAddressOfRemoteServer();
- if (serverUrl == null) {
- throw new IllegalArgumentException("The Appium server address is not set");
- }
- return serverUrl;
- }
-
- /**
- * Builds the logcat web socket URI.
- * The socket is registered at the server root, so {@code serverUrl}'s HTTP base path is not included.
- *
- * @param serverUrl the Appium server the driver is connected to. Only its scheme is used.
- * @param host the socket host
- * @param port the socket port, or a negative value to omit the port
- * @param sessionId the current session id
- * @return the absolute web socket URI
- */
- private static URI buildLogcatEndpoint(URL serverUrl, String host, int port, String sessionId) {
- try {
- return new URI(getWebsocketScheme(serverUrl.getProtocol()), null, requireNonNull(host, "Host"), port,
- "/ws/session/" + sessionId + "/appium/device/logcat", null, null);
- } catch (URISyntaxException e) {
- throw new IllegalArgumentException("Cannot build the logcat web socket endpoint", e);
- }
- }
-
- private static String getWebsocketScheme(String protocol) {
- return "https".equalsIgnoreCase(protocol) || "wss".equalsIgnoreCase(protocol) ? "wss" : "ws";
+ LogBroadcastEndpoints.startBroadcast(this, this::getLogcatClient, host, port, "logcat");
}
/**
diff --git a/src/main/java/io/appium/java_client/internal/CommandExecutorInternals.java b/src/main/java/io/appium/java_client/internal/CommandExecutorInternals.java
new file mode 100644
index 000000000..eeccaa27a
--- /dev/null
+++ b/src/main/java/io/appium/java_client/internal/CommandExecutorInternals.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * See the NOTICE file distributed with this work for additional
+ * information regarding copyright ownership.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package io.appium.java_client.internal;
+
+import io.appium.java_client.remote.AppiumCommandExecutor;
+import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
+
+import java.lang.invoke.MethodHandles;
+import java.net.URL;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Internal bridge exposing private command executor state without widening public API.
+ *
+ * @deprecated The logs broadcasting web socket of the Appium drivers is deprecated and will be removed
+ * together with this API. Subscribe to the BiDi {@code log.entryAdded} event instead, see the
+ * Selenium
+ * bridge documentation.
+ */
+@NullMarked
+@Deprecated(since = "11.1.0", forRemoval = true)
+@SuppressWarnings("removal")
+public final class CommandExecutorInternals {
+ private static final AtomicReference<@Nullable Function>
+ INITIAL_SERVER_URL_RESOLVER = new AtomicReference<>();
+
+ private CommandExecutorInternals() {
+ }
+
+ /**
+ * Registers the internal resolver that reads an executor's initial server URL before any URL overrides.
+ *
+ * @param lookup a private lookup belonging to {@link AppiumCommandExecutor}
+ * @param resolver the function returning the initial server URL for an executor
+ * @throws SecurityException if {@code lookup} does not have private access to {@link AppiumCommandExecutor}
+ */
+ @Deprecated(since = "11.1.0", forRemoval = true)
+ public static void registerInitialServerUrlResolver(
+ MethodHandles.Lookup lookup,
+ Function resolver
+ ) {
+ requireNonNull(lookup, "Lookup");
+ requireNonNull(resolver, "Resolver");
+ if (lookup.lookupClass() != AppiumCommandExecutor.class
+ || (lookup.lookupModes() & MethodHandles.Lookup.PRIVATE) == 0) {
+ throw new SecurityException(
+ "Only AppiumCommandExecutor may register the initial server URL resolver"
+ );
+ }
+ INITIAL_SERVER_URL_RESOLVER.compareAndSet(null, resolver);
+ }
+
+ /**
+ * Returns the server URL configured on {@code executor} before any {@code directConnect} or
+ * {@code overrideServerUrl} override took effect.
+ *
+ * @param executor the command executor to inspect
+ * @return the initial server URL, or {@code null} if none was configured
+ */
+ @Nullable
+ @Deprecated(since = "11.1.0", forRemoval = true)
+ public static URL getInitialServerUrl(AppiumCommandExecutor executor) {
+ requireNonNull(executor, "Command executor");
+ Function resolver = INITIAL_SERVER_URL_RESOLVER.get();
+ return resolver != null ? resolver.apply(executor) : executor.getAddressOfRemoteServer();
+ }
+}
diff --git a/src/main/java/io/appium/java_client/internal/LogBroadcastEndpoints.java b/src/main/java/io/appium/java_client/internal/LogBroadcastEndpoints.java
new file mode 100644
index 000000000..f950afac3
--- /dev/null
+++ b/src/main/java/io/appium/java_client/internal/LogBroadcastEndpoints.java
@@ -0,0 +1,183 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * See the NOTICE file distributed with this work for additional
+ * information regarding copyright ownership.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package io.appium.java_client.internal;
+
+import io.appium.java_client.CommandExecutionHelper;
+import io.appium.java_client.ExecutesMethod;
+import io.appium.java_client.remote.AppiumCommandExecutor;
+import io.appium.java_client.remote.AppiumRemoteWebDriver;
+import io.appium.java_client.remote.SessionId;
+import io.appium.java_client.ws.StringWebSocketClient;
+import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.function.Supplier;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Shared endpoint resolution and WebSocket startup helpers for device log broadcast listeners.
+ *
+ * @deprecated The logs broadcasting web socket of the Appium drivers is deprecated and will be removed
+ * together with this API. Subscribe to the BiDi {@code log.entryAdded} event instead, see the
+ * Selenium
+ * bridge documentation.
+ */
+@NullMarked
+@Deprecated(since = "11.1.0", forRemoval = true)
+@SuppressWarnings("removal")
+public final class LogBroadcastEndpoints {
+ private LogBroadcastEndpoints() {
+ }
+
+ /**
+ * Starts server-side log streaming and connects the WebSocket client to the currently connected
+ * Appium server endpoint using its host, port, and scheme.
+ *
+ * @param driver the driver executing {@code mobile: startLogsBroadcast}
+ * @param clientSupplier supplier for the target WebSocket client, invoked after starting server streaming
+ * @param deviceLogType the log endpoint suffix (such as {@code logcat} or {@code syslog})
+ */
+ @Deprecated(since = "11.1.0", forRemoval = true)
+ public static void startBroadcast(
+ ExecutesMethod driver,
+ Supplier clientSupplier,
+ String deviceLogType
+ ) {
+ var remoteWebDriver = (AppiumRemoteWebDriver) driver;
+ var executor = (AppiumCommandExecutor) remoteWebDriver.getCommandExecutor();
+ URL serverUrl = executor.getAddressOfRemoteServer();
+ if (serverUrl == null) {
+ throw new IllegalArgumentException("The Appium server address is not set");
+ }
+ startBroadcast(
+ remoteWebDriver,
+ driver,
+ clientSupplier,
+ serverUrl,
+ serverUrl.getHost(),
+ serverUrl.getPort(),
+ deviceLogType
+ );
+ }
+
+ /**
+ * Starts server-side log streaming and connects the WebSocket client to the broadcast endpoint.
+ * The WebSocket scheme ({@code ws} or {@code wss}) is derived from the executor's initial server URL
+ * before any {@code directConnect} or server URL override so existing callers keep their original scheme.
+ *
+ * @param driver the driver executing {@code mobile: startLogsBroadcast}
+ * @param clientSupplier supplier for the target WebSocket client, invoked after starting server streaming
+ * @param host the target WebSocket host
+ * @param port the target WebSocket port, or a negative value to omit the port
+ * @param deviceLogType the log endpoint suffix (such as {@code logcat} or {@code syslog})
+ */
+ @Deprecated(since = "11.1.0", forRemoval = true)
+ public static void startBroadcast(
+ ExecutesMethod driver,
+ Supplier clientSupplier,
+ String host,
+ int port,
+ String deviceLogType
+ ) {
+ var remoteWebDriver = (AppiumRemoteWebDriver) driver;
+ var executor = (AppiumCommandExecutor) remoteWebDriver.getCommandExecutor();
+ startBroadcast(
+ remoteWebDriver,
+ driver,
+ clientSupplier,
+ CommandExecutorInternals.getInitialServerUrl(executor),
+ host,
+ port,
+ deviceLogType
+ );
+ }
+
+ private static void startBroadcast(
+ AppiumRemoteWebDriver remoteWebDriver,
+ ExecutesMethod driver,
+ Supplier clientSupplier,
+ @Nullable URL serverUrl,
+ String host,
+ int port,
+ String deviceLogType
+ ) {
+ URI endpoint = buildBroadcastUri(
+ serverUrl,
+ host,
+ port,
+ remoteWebDriver.getSessionId(),
+ deviceLogType
+ );
+ CommandExecutionHelper.executeScript(driver, "mobile: startLogsBroadcast");
+ clientSupplier.get().connect(endpoint);
+ }
+
+ /**
+ * Builds a device log broadcast WebSocket URI using {@code wss} when {@code serverUrl} uses
+ * {@code https} or {@code wss}, or {@code ws} otherwise.
+ *
+ * @param serverUrl the server URL used to choose the WebSocket scheme, or {@code null} if unknown
+ * @param host the target WebSocket host (bare IPv6 literals are bracketed automatically)
+ * @param port the target WebSocket port, or a negative value to omit the port
+ * @param sessionId the active session identifier
+ * @param deviceLogType the log endpoint suffix (such as {@code logcat} or {@code syslog})
+ * @return the WebSocket endpoint URI
+ */
+ @Deprecated(since = "11.1.0", forRemoval = true)
+ public static URI buildBroadcastUri(
+ @Nullable URL serverUrl,
+ String host,
+ int port,
+ @Nullable SessionId sessionId,
+ String deviceLogType
+ ) {
+ String protocol = serverUrl == null ? null : serverUrl.getProtocol();
+ String scheme = "https".equalsIgnoreCase(protocol) || "wss".equalsIgnoreCase(protocol) ? "wss" : "ws";
+ String validatedHost = requireNonNull(host, "Host");
+ if (validatedHost.isBlank()) {
+ throw new IllegalArgumentException("Host must not be blank");
+ }
+ String path = "/ws/session/" + sessionId + "/appium/device/" + deviceLogType;
+ int normalizedPort = port < 0 ? -1 : port;
+ try {
+ URI endpoint = new URI(
+ scheme,
+ null,
+ Strings.formatHost(validatedHost),
+ normalizedPort,
+ path,
+ null,
+ null
+ );
+ if (endpoint.getHost() == null
+ || endpoint.getPort() != normalizedPort
+ || endpoint.getRawUserInfo() != null
+ || endpoint.getRawQuery() != null
+ || endpoint.getRawFragment() != null
+ || !path.equals(endpoint.getPath())) {
+ throw new IllegalArgumentException("Cannot build the log broadcast web socket endpoint");
+ }
+ return endpoint;
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException("Cannot build the log broadcast web socket endpoint", e);
+ }
+ }
+}
diff --git a/src/main/java/io/appium/java_client/internal/Strings.java b/src/main/java/io/appium/java_client/internal/Strings.java
index 4cee7b0ae..d8f5946f3 100644
--- a/src/main/java/io/appium/java_client/internal/Strings.java
+++ b/src/main/java/io/appium/java_client/internal/Strings.java
@@ -34,4 +34,20 @@ private Strings() {
public static boolean isNullOrEmpty(@Nullable String string) {
return string == null || string.isEmpty();
}
+
+ /**
+ * Wraps a bare IPv6 host literal in brackets if not already bracketed.
+ *
+ * @param host the host name or IP literal
+ * @return the URL-safe host representation
+ */
+ public static String formatHost(String host) {
+ if (!host.startsWith("[")) {
+ int firstColon = host.indexOf(':');
+ if (firstColon >= 0 && host.indexOf(':', firstColon + 1) >= 0) {
+ return "[" + host + "]";
+ }
+ }
+ return host;
+ }
}
diff --git a/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java b/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java
index d6bbc406f..46c1d83bb 100644
--- a/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java
+++ b/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java
@@ -18,13 +18,9 @@
import io.appium.java_client.CommandExecutionHelper;
import io.appium.java_client.ExecutesMethod;
-import io.appium.java_client.remote.AppiumCommandExecutor;
-import io.appium.java_client.remote.AppiumRemoteWebDriver;
-import io.appium.java_client.remote.SessionId;
+import io.appium.java_client.internal.LogBroadcastEndpoints;
import io.appium.java_client.ws.StringWebSocketClient;
-import java.net.URI;
-import java.net.URL;
import java.util.function.Consumer;
import static io.appium.java_client.service.local.AppiumServiceBuilder.DEFAULT_APPIUM_PORT;
@@ -62,6 +58,8 @@ default void startSyslogBroadcast() {
/**
* Start syslog messages broadcast via web socket.
* This method assumes that Appium server is assigned to the default port (4723).
+ * The scheme follows the initial Appium server URL configured on the executor,
+ * defaulting to {@code ws} if unset.
*
* @param host the name of the host where Appium server is running
*/
@@ -72,19 +70,16 @@ default void startSyslogBroadcast(String host) {
/**
* Start syslog messages broadcast via web socket.
+ * The scheme follows the initial Appium server URL configured on the executor,
+ * defaulting to {@code ws} if unset.
*
* @param host the name of the host where Appium server is running
- * @param port the port of the host where Appium server is running
+ * @param port the port of the host where Appium server is running.
+ * A negative port means the scheme default and is omitted from the URI.
*/
@Deprecated(since = "11.1.0", forRemoval = true)
default void startSyslogBroadcast(String host, int port) {
- var remoteWebDriver = (AppiumRemoteWebDriver) this;
- URL serverUrl = ((AppiumCommandExecutor) remoteWebDriver.getCommandExecutor()).getAddressOfRemoteServer();
- var scheme = "https".equals(serverUrl.getProtocol()) ? "wss" : "ws";
- CommandExecutionHelper.executeScript(this, "mobile: startLogsBroadcast");
- SessionId sessionId = remoteWebDriver.getSessionId();
- var endpoint = String.format("%s://%s:%s/ws/session/%s/appium/device/syslog", scheme, host, port, sessionId);
- getSyslogClient().connect(URI.create(endpoint));
+ LogBroadcastEndpoints.startBroadcast(this, this::getSyslogClient, host, port, "syslog");
}
/**
diff --git a/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java b/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java
index aea8263c9..c9b435146 100644
--- a/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java
+++ b/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java
@@ -22,6 +22,7 @@
import io.appium.java_client.http.HttpClient.Factory;
import io.appium.java_client.http.HttpRequest;
import io.appium.java_client.http.HttpResponse;
+import io.appium.java_client.internal.CommandExecutorInternals;
import io.appium.java_client.internal.DirectConnectUrlSafety;
import io.appium.java_client.internal.webdriver.ProtocolHandshake;
import io.appium.java_client.service.local.AppiumDriverLocalService;
@@ -34,6 +35,7 @@
import org.openqa.selenium.WebDriverException;
import java.io.Closeable;
+import java.lang.invoke.MethodHandles;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
@@ -54,16 +56,55 @@ public class AppiumCommandExecutor implements CommandExecutor, Closeable {
private static final String JSON_UTF_8 = "application/json; charset=utf-8";
private final Optional serviceOptional;
- @Getter
- private final AppiumClientConfig appiumClientConfig;
- private final @Nullable URL remoteServer;
private final Map additionalCommands;
@Getter
private final Factory httpClientFactory;
- private HttpClient client;
+ private final Object clientStateLock = new Object();
+ @Deprecated(since = "11.1.0", forRemoval = true)
+ private final @Nullable URL initialServerUrl;
+ private volatile ClientState clientState;
private @Nullable CommandCodec commandCodec;
private @Nullable ResponseCodec responseCodec;
+ static {
+ registerInitialServerUrlResolver();
+ }
+
+ /**
+ * Registers the internal initial-URL resolver used by the deprecated logs broadcasting web socket API.
+ *
+ * @deprecated Only used by the deprecated logs broadcasting web socket API and will be removed together with it.
+ */
+ @Deprecated(since = "11.1.0", forRemoval = true)
+ @SuppressWarnings("removal")
+ private static void registerInitialServerUrlResolver() {
+ CommandExecutorInternals.registerInitialServerUrlResolver(
+ MethodHandles.lookup(),
+ AppiumCommandExecutor::resolveInitialServerUrl
+ );
+ }
+
+ private static final class ClientState {
+ private final AppiumClientConfig config;
+ private final HttpClient client;
+ private final @Nullable URL remoteServer;
+ @Deprecated(since = "11.1.0", forRemoval = true)
+ private final boolean serverUrlOverridden;
+
+ @SuppressWarnings("removal")
+ private ClientState(
+ AppiumClientConfig config,
+ HttpClient client,
+ @Nullable URL remoteServer,
+ boolean serverUrlOverridden
+ ) {
+ this.config = config;
+ this.client = client;
+ this.remoteServer = remoteServer;
+ this.serverUrlOverridden = serverUrlOverridden;
+ }
+ }
+
/**
* Create an AppiumCommandExecutor instance.
*
@@ -78,10 +119,19 @@ public AppiumCommandExecutor(
@Nullable Factory httpClientFactory,
AppiumClientConfig appiumClientConfig) {
this.additionalCommands = new HashMap<>(requireNonNull(additionalCommands, "Additional commands"));
- this.appiumClientConfig = requireNonNull(appiumClientConfig, "HTTP client configuration");
+ AppiumClientConfig effectiveConfig = requireNonNull(appiumClientConfig, "HTTP client configuration");
+ if (service != null && effectiveConfig.baseUri() == null) {
+ effectiveConfig = effectiveConfig.baseUrl(service.getUrl());
+ }
+ URL initialUrl = effectiveConfig.baseUrl();
+ this.initialServerUrl = initialUrl;
this.httpClientFactory = ofNullable(httpClientFactory).orElseGet(Factory::createDefault);
- this.client = this.httpClientFactory.createClient(appiumClientConfig);
- this.remoteServer = appiumClientConfig.baseUrl();
+ this.clientState = new ClientState(
+ effectiveConfig,
+ this.httpClientFactory.createClient(effectiveConfig),
+ initialUrl,
+ false
+ );
this.serviceOptional = ofNullable(service);
}
@@ -163,11 +213,12 @@ public AppiumCommandExecutor(Map additionalCommands,
* Creates an executor that talks to a local Appium service using the given client configuration.
*
* @param additionalCommands the map of Appium commands
- * @param service the local Appium service to send the commands to
+ * @param service the local Appium service to send the commands to, or {@code null} if none
* @param appiumClientConfig the HTTP client configuration
*/
public AppiumCommandExecutor(Map additionalCommands,
- AppiumDriverLocalService service, AppiumClientConfig appiumClientConfig) {
+ @Nullable AppiumDriverLocalService service,
+ AppiumClientConfig appiumClientConfig) {
this(additionalCommands, service, Factory.createDefault(), appiumClientConfig);
}
@@ -180,6 +231,15 @@ public Map getAdditionalCommands() {
return Collections.unmodifiableMap(additionalCommands);
}
+ /**
+ * Returns the HTTP client configuration used by this executor.
+ *
+ * @return the HTTP client configuration
+ */
+ public AppiumClientConfig getAppiumClientConfig() {
+ return clientState.config;
+ }
+
/**
* The address of the server the commands are sent to.
*
@@ -187,7 +247,22 @@ public Map getAdditionalCommands() {
*/
@Nullable
public URL getAddressOfRemoteServer() {
- return remoteServer;
+ return clientState.remoteServer;
+ }
+
+ @Nullable
+ @Deprecated(since = "11.1.0", forRemoval = true)
+ @SuppressWarnings("removal")
+ private static URL resolveInitialServerUrl(AppiumCommandExecutor executor) {
+ ClientState state = executor.clientState;
+ if (state == null) {
+ return executor.getAddressOfRemoteServer();
+ }
+ if (state.serverUrlOverridden || executor.getClass() == AppiumCommandExecutor.class) {
+ return executor.initialServerUrl;
+ }
+ URL current = executor.getAddressOfRemoteServer();
+ return executor.clientState.serverUrlOverridden ? executor.initialServerUrl : current;
}
/**
@@ -224,7 +299,7 @@ public void setResponseCodec(ResponseCodec codec) {
* @return the HTTP client
*/
public HttpClient getClient() {
- return this.client;
+ return clientState.client;
}
/**
@@ -240,11 +315,16 @@ public HttpClient getClient() {
* and other non-special addresses are not rejected by this check.
*/
protected void overrideServerUrl(URL serverUrl) {
- DirectConnectUrlSafety.requireSafeOverrideTarget(serverUrl);
- HttpClient newClient = getHttpClientFactory().createClient(appiumClientConfig.baseUrl(serverUrl));
- HttpClient oldClient = this.client;
- this.client = newClient;
- oldClient.close();
+ DirectConnectUrlSafety.requireSafeOverrideTarget(requireNonNull(serverUrl, "Server URL"));
+ ClientState previousState;
+ synchronized (clientStateLock) {
+ previousState = this.clientState;
+ AppiumClientConfig updatedConfig = previousState.config.baseUrl(serverUrl);
+ URL updatedServerUrl = updatedConfig.baseUrl();
+ HttpClient newClient = getHttpClientFactory().createClient(updatedConfig);
+ this.clientState = new ClientState(updatedConfig, newClient, updatedServerUrl, true);
+ }
+ previousState.client.close();
}
private Response createSession(Command command) {
@@ -257,7 +337,7 @@ private Response createSession(Command command) {
refreshAdditionalCommands();
setResponseCodec(new AppiumW3CHttpResponseCodec());
Response response = result.createResponse();
- if (appiumClientConfig.isDirectConnectEnabled()) {
+ if (getAppiumClientConfig().isDirectConnectEnabled()) {
setDirectConnect(response);
}
@@ -292,7 +372,7 @@ private void setDirectConnect(Response response) throws SessionNotCreatedExcepti
return;
}
- if (!directConnect.getProtocol().equals("https")) {
+ if (!"https".equalsIgnoreCase(directConnect.getProtocol())) {
throw new SessionNotCreatedException(
String.format("The given protocol '%s' as the direct connection url returned by "
+ "the remote server is not accurate. Only 'https' is supported.",
@@ -363,8 +443,9 @@ private Response executeInSession(Command command) {
httpRequest.addHeader("Content-Type", JSON_UTF_8);
}
+ HttpClient activeClient = getClient();
try {
- HttpResponse httpResponse = client.execute(httpRequest);
+ HttpResponse httpResponse = activeClient.execute(httpRequest);
Response response = responseCodec.decode(httpResponse);
if (response.getSessionId() == null) {
@@ -372,7 +453,7 @@ private Response executeInSession(Command command) {
response.setSessionId(command.getSessionId().toString());
}
if (DriverCommand.QUIT.equals(command.getName())) {
- client.close();
+ activeClient.close();
}
return response;
} catch (UnsupportedCommandException e) {
@@ -394,6 +475,6 @@ private static Throwable getRootCause(Throwable throwable) {
@Override
public void close() {
- client.close();
+ getClient().close();
}
}
diff --git a/src/main/java/io/appium/java_client/remote/DirectConnect.java b/src/main/java/io/appium/java_client/remote/DirectConnect.java
index c191c6eb8..76b639f8b 100644
--- a/src/main/java/io/appium/java_client/remote/DirectConnect.java
+++ b/src/main/java/io/appium/java_client/remote/DirectConnect.java
@@ -16,11 +16,13 @@
package io.appium.java_client.remote;
+import io.appium.java_client.internal.Strings;
import lombok.AccessLevel;
import lombok.Getter;
import org.jspecify.annotations.Nullable;
import java.net.MalformedURLException;
+import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import java.util.Objects;
@@ -78,15 +80,38 @@ public boolean isValid() {
* @throws MalformedURLException if the built url was invalid
*/
public URL getUrl() throws MalformedURLException {
- String newUrlCandidate = String.format("%s://%s:%s%s", this.protocol, this.host, this.port, this.path);
+ if (!isValid()
+ || this.protocol.isBlank()
+ || this.host.isBlank()
+ || this.port.isBlank()
+ || !this.path.isEmpty() && this.path.isBlank()) {
+ throw createMalformedUrlException(
+ this.protocol + "://" + this.host + ":" + this.port + this.path
+ );
+ }
+ String newUrlCandidate = this.protocol + "://" + Strings.formatHost(this.host)
+ + ":" + this.port + normalizePath(this.path);
try {
- return new URL(newUrlCandidate);
- } catch (MalformedURLException e) {
- throw new MalformedURLException(
- String.format("The remote server returned an invalid value to build the direct connect URL: %s",
- newUrlCandidate)
- );
+ URL url = new URL(newUrlCandidate);
+ url.toURI();
+ return url;
+ } catch (MalformedURLException | URISyntaxException e) {
+ throw createMalformedUrlException(newUrlCandidate);
+ }
+ }
+
+ private static String normalizePath(String path) {
+ if (path.isEmpty() || path.startsWith("/")) {
+ return path;
}
+ return "/" + path;
+ }
+
+ private static MalformedURLException createMalformedUrlException(String candidate) {
+ return new MalformedURLException(
+ String.format("The remote server returned an invalid value to build the direct connect URL: %s",
+ candidate)
+ );
}
}
diff --git a/src/test/java/io/appium/java_client/internal/DirectConnectTest.java b/src/test/java/io/appium/java_client/internal/DirectConnectTest.java
index 8255c3c5d..15f653761 100644
--- a/src/test/java/io/appium/java_client/internal/DirectConnectTest.java
+++ b/src/test/java/io/appium/java_client/internal/DirectConnectTest.java
@@ -55,5 +55,109 @@ void hasInvalidDirectConnect() {
Map responseValue = new HashMap<>();
DirectConnect directConnect = new DirectConnect(responseValue);
assertFalse(directConnect.isValid());
+ assertThrowsExactly(MalformedURLException.class, directConnect::getUrl);
+ }
+
+ @Test
+ void formatsBareIpv6HostAndPreservesBracketedIpv6Host() throws MalformedURLException {
+ Map bareIpv6 = Map.of(
+ "appium:directConnectProtocol", "https",
+ "appium:directConnectHost", "2001:db8::1",
+ "appium:directConnectPort", "4443",
+ "appium:directConnectPath", "/wd/hub"
+ );
+ DirectConnect bare = new DirectConnect(bareIpv6);
+ assertTrue(bare.isValid());
+ assertEquals("https://[2001:db8::1]:4443/wd/hub", bare.getUrl().toString());
+
+ Map bracketedIpv6 = Map.of(
+ "appium:directConnectProtocol", "https",
+ "appium:directConnectHost", "[2001:db8::1]",
+ "appium:directConnectPort", "4443",
+ "appium:directConnectPath", "/wd/hub"
+ );
+ DirectConnect bracketed = new DirectConnect(bracketedIpv6);
+ assertTrue(bracketed.isValid());
+ assertEquals("https://[2001:db8::1]:4443/wd/hub", bracketed.getUrl().toString());
+ assertEquals("[2001:db8::1]", Strings.formatHost("2001:db8::1"));
+ assertEquals("[2001:db8::1]", Strings.formatHost("[2001:db8::1]"));
+ }
+
+ @Test
+ void normalizesEmptyAndRelativeDirectConnectPath() throws MalformedURLException {
+ DirectConnect emptyPath = new DirectConnect(Map.of(
+ "appium:directConnectProtocol", "https",
+ "appium:directConnectHost", "203.0.113.1",
+ "appium:directConnectPort", "4443",
+ "appium:directConnectPath", ""
+ ));
+ assertTrue(emptyPath.isValid());
+ assertEquals("https://203.0.113.1:4443", emptyPath.getUrl().toString());
+
+ DirectConnect relativePath = new DirectConnect(Map.of(
+ "appium:directConnectProtocol", "https",
+ "appium:directConnectHost", "203.0.113.1",
+ "appium:directConnectPort", "4443",
+ "appium:directConnectPath", "wd/hub"
+ ));
+ assertTrue(relativePath.isValid());
+ assertEquals("https://203.0.113.1:4443/wd/hub", relativePath.getUrl().toString());
+ }
+
+ @Test
+ void rejectsSingleColonHostAndBlankFields() {
+ DirectConnect embeddedPortHost = new DirectConnect(Map.of(
+ "appium:directConnectProtocol", "https",
+ "appium:directConnectHost", "evil.example.com:8443",
+ "appium:directConnectPort", "4443",
+ "appium:directConnectPath", "/wd/hub"
+ ));
+ assertTrue(embeddedPortHost.isValid());
+ assertThrowsExactly(MalformedURLException.class, embeddedPortHost::getUrl);
+
+ DirectConnect blankHost = new DirectConnect(Map.of(
+ "appium:directConnectProtocol", "https",
+ "appium:directConnectHost", " ",
+ "appium:directConnectPort", "4443",
+ "appium:directConnectPath", ""
+ ));
+ assertTrue(blankHost.isValid());
+ assertThrowsExactly(MalformedURLException.class, blankHost::getUrl);
+
+ DirectConnect blankPort = new DirectConnect(Map.of(
+ "appium:directConnectProtocol", "https",
+ "appium:directConnectHost", "x",
+ "appium:directConnectPort", "",
+ "appium:directConnectPath", "/wd/hub"
+ ));
+ assertTrue(blankPort.isValid());
+ assertThrowsExactly(MalformedURLException.class, blankPort::getUrl);
+
+ DirectConnect blankProtocol = new DirectConnect(Map.of(
+ "appium:directConnectProtocol", " ",
+ "appium:directConnectHost", "203.0.113.1",
+ "appium:directConnectPort", "4443",
+ "appium:directConnectPath", "/wd/hub"
+ ));
+ assertTrue(blankProtocol.isValid());
+ assertThrowsExactly(MalformedURLException.class, blankProtocol::getUrl);
+
+ DirectConnect whitespacePath = new DirectConnect(Map.of(
+ "appium:directConnectProtocol", "https",
+ "appium:directConnectHost", "203.0.113.1",
+ "appium:directConnectPort", "4443",
+ "appium:directConnectPath", " "
+ ));
+ assertTrue(whitespacePath.isValid());
+ assertThrowsExactly(MalformedURLException.class, whitespacePath::getUrl);
+
+ DirectConnect spaceInPath = new DirectConnect(Map.of(
+ "appium:directConnectProtocol", "https",
+ "appium:directConnectHost", "203.0.113.1",
+ "appium:directConnectPort", "4443",
+ "appium:directConnectPath", " wd/hub"
+ ));
+ assertTrue(spaceInPath.isValid());
+ assertThrowsExactly(MalformedURLException.class, spaceInPath::getUrl);
}
}
diff --git a/src/test/java/io/appium/java_client/internal/LogBroadcastEndpointsTest.java b/src/test/java/io/appium/java_client/internal/LogBroadcastEndpointsTest.java
new file mode 100644
index 000000000..9aa014866
--- /dev/null
+++ b/src/test/java/io/appium/java_client/internal/LogBroadcastEndpointsTest.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * See the NOTICE file distributed with this work for additional
+ * information regarding copyright ownership.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package io.appium.java_client.internal;
+
+import io.appium.java_client.remote.SessionId;
+import org.junit.jupiter.api.Test;
+
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@SuppressWarnings("removal")
+class LogBroadcastEndpointsTest {
+
+ @Test
+ void derivesWebSocketSchemeFromServerUrlAndFormatsIpv6Hosts() throws MalformedURLException {
+ SessionId sessionId = new SessionId("s1");
+
+ URI nullServer = LogBroadcastEndpoints.buildBroadcastUri(
+ null, "127.0.0.1", 4723, sessionId, "logcat"
+ );
+ assertEquals("ws://127.0.0.1:4723/ws/session/s1/appium/device/logcat", nullServer.toString());
+
+ URI httpServer = LogBroadcastEndpoints.buildBroadcastUri(
+ new URL("http://hub.example.com:4723"), "hub.example.com", 4723, sessionId, "logcat"
+ );
+ assertEquals("ws://hub.example.com:4723/ws/session/s1/appium/device/logcat", httpServer.toString());
+
+ URI httpsServer = LogBroadcastEndpoints.buildBroadcastUri(
+ new URL("https://direct.example.com:4443"), "2001:db8::1", 4443, sessionId, "syslog"
+ );
+ assertEquals("wss://[2001:db8::1]:4443/ws/session/s1/appium/device/syslog", httpsServer.toString());
+
+ URI uppercaseHttpsServer = LogBroadcastEndpoints.buildBroadcastUri(
+ new URL("HTTPS://direct.example.com:4443"), "[2001:db8::1]", 4443, sessionId, "logcat"
+ );
+ assertEquals("wss://[2001:db8::1]:4443/ws/session/s1/appium/device/logcat", uppercaseHttpsServer.toString());
+
+ URI omittedPort = LogBroadcastEndpoints.buildBroadcastUri(
+ new URL("https://direct.example.com/wd/hub"), "direct.example.com", -1, sessionId, "logcat"
+ );
+ assertEquals("wss://direct.example.com/ws/session/s1/appium/device/logcat", omittedPort.toString());
+ }
+
+ @Test
+ void rejectsBlankOrMalformedHosts() {
+ SessionId sessionId = new SessionId("s1");
+ for (String invalidHost : List.of(
+ "", " ", "evil.com:9000", "user@host", "host/path", "host?q", "host#frag")) {
+ assertThrows(IllegalArgumentException.class,
+ () -> LogBroadcastEndpoints.buildBroadcastUri(null, invalidHost, 4723, sessionId, "logcat"));
+ assertThrows(IllegalArgumentException.class,
+ () -> LogBroadcastEndpoints.buildBroadcastUri(null, invalidHost, -1, sessionId, "logcat"));
+ }
+ }
+}
diff --git a/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java b/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java
index b11bd6273..352326e45 100644
--- a/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java
+++ b/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java
@@ -2,18 +2,96 @@
import io.appium.java_client.AppiumClientConfig;
import io.appium.java_client.MobileCommand;
+import io.appium.java_client.android.AndroidDriver;
+import io.appium.java_client.android.options.UiAutomator2Options;
+import io.appium.java_client.http.ClientConfig;
+import io.appium.java_client.http.Contents;
+import io.appium.java_client.http.HttpClient;
+import io.appium.java_client.http.HttpRequest;
+import io.appium.java_client.http.HttpResponse;
+import io.appium.java_client.http.Message;
+import io.appium.java_client.http.WebSocket;
+import io.appium.java_client.internal.CommandExecutorInternals;
+import io.appium.java_client.ios.IOSDriver;
+import io.appium.java_client.ios.options.XCUITestOptions;
+import io.appium.java_client.service.local.AppiumDriverLocalService;
+import io.appium.java_client.service.local.AppiumServiceBuilder;
+import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.openqa.selenium.SessionNotCreatedException;
+import java.io.File;
+import java.io.IOException;
+import java.lang.invoke.MethodHandles;
import java.net.MalformedURLException;
+import java.net.URI;
import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
class AppiumCommandExecutorTest {
private static final String APPIUM_URL = "https://appium.example.com";
+ private static final File NODE = new File(Path.of(System.getProperty("java.home"), "bin", "java").toString());
+
+ @TempDir
+ Path tempDir;
+
+ private static final class RecordingHttpClient implements HttpClient {
+ private final ClientConfig config;
+ private final AtomicBoolean closed = new AtomicBoolean(false);
+ private final String sessionCapabilitiesJson;
+ private final List socketUris = new ArrayList<>();
+
+ RecordingHttpClient(ClientConfig config, String sessionCapabilitiesJson) {
+ this.config = config;
+ this.sessionCapabilitiesJson = sessionCapabilitiesJson;
+ }
+
+ @Override
+ public HttpResponse execute(HttpRequest request) {
+ String body = "/session".equals(request.getUri())
+ ? "{\"value\":{\"sessionId\":\"s1\",\"capabilities\":" + sessionCapabilitiesJson + "}}"
+ : "{\"value\":null}";
+ return new HttpResponse()
+ .setStatus(200)
+ .setHeader("Content-Type", "application/json; charset=utf-8")
+ .setContent(Contents.utf8String(body));
+ }
+
+ @Override
+ public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener) {
+ socketUris.add(request.getUri());
+ return new WebSocket() {
+ @Override
+ public WebSocket send(Message message) {
+ return this;
+ }
+
+ @Override
+ public void close() {
+ }
+ };
+ }
+
+ @Override
+ public void close() {
+ closed.set(true);
+ }
+ }
private AppiumCommandExecutor createExecutor() {
URL baseUrl;
@@ -38,12 +116,456 @@ void getHttpClientFactory() {
@Test
void overrideServerUrl() throws MalformedURLException {
- assertDoesNotThrow(() -> createExecutor().overrideServerUrl(new URL("https://203.0.113.1/wd/hub")));
+ List created = new ArrayList<>();
+ HttpClient.Factory factory = cfg -> {
+ RecordingHttpClient client = new RecordingHttpClient(cfg, "{\"platformName\":\"Android\"}");
+ created.add(client);
+ return client;
+ };
+ AppiumClientConfig initialConfig = AppiumClientConfig.defaultConfig()
+ .baseUrl(new URL(APPIUM_URL))
+ .readTimeout(Duration.ofSeconds(45));
+ AppiumCommandExecutor executor = new AppiumCommandExecutor(
+ MobileCommand.commandRepository, null, factory, initialConfig);
+ final HttpClient firstClient = executor.getClient();
+
+ URL overrideUrl = new URL("https://203.0.113.1:4443/wd/hub");
+ executor.overrideServerUrl(overrideUrl);
+
+ assertEquals(2, created.size());
+ assertTrue(created.get(0).closed.get());
+ assertFalse(created.get(1).closed.get());
+ assertNotSame(firstClient, executor.getClient());
+ assertSame(created.get(1), executor.getClient());
+ assertEquals(overrideUrl, executor.getAddressOfRemoteServer());
+ assertEquals(overrideUrl, executor.getAppiumClientConfig().baseUrl());
+ assertEquals(URI.create("https://203.0.113.1:4443/wd/hub"), created.get(1).config.baseUri());
+ assertEquals(Duration.ofSeconds(45), created.get(1).config.readTimeout());
+ assertEquals(URI.create("https://203.0.113.1:4443/wd/hub"), executor.getAppiumClientConfig().baseUri());
+ assertEquals(Duration.ofSeconds(45), executor.getAppiumClientConfig().readTimeout());
}
@Test
void overrideServerUrlRejectsLoopbackTarget() throws MalformedURLException {
+ List created = new ArrayList<>();
+ HttpClient.Factory factory = cfg -> {
+ RecordingHttpClient client = new RecordingHttpClient(cfg, "{\"platformName\":\"Android\"}");
+ created.add(client);
+ return client;
+ };
+ URL initialUrl = new URL(APPIUM_URL);
+ AppiumCommandExecutor executor = new AppiumCommandExecutor(
+ MobileCommand.commandRepository, null, factory,
+ AppiumClientConfig.defaultConfig().baseUrl(initialUrl));
+
assertThrows(SessionNotCreatedException.class,
- () -> createExecutor().overrideServerUrl(new URL("https://127.0.0.1:4443/wd/hub")));
+ () -> executor.overrideServerUrl(new URL("https://127.0.0.1:4443/wd/hub")));
+ assertEquals(1, created.size());
+ assertFalse(created.get(0).closed.get());
+ assertEquals(initialUrl, executor.getAddressOfRemoteServer());
+ assertEquals(initialUrl, executor.getAppiumClientConfig().baseUrl());
+ }
+
+ @Test
+ void populatesBaseUrlFromLocalServiceWhenUnsetInClientConfig() throws IOException {
+ File mainJs = Files.createFile(tempDir.resolve("main.js")).toFile();
+ var service = new AppiumServiceBuilder()
+ .usingDriverExecutable(NODE)
+ .withAppiumJS(mainJs)
+ .usingPort(4777)
+ .withIPAddress("127.0.0.1")
+ .build();
+ AppiumClientConfig customConfig = AppiumClientConfig.defaultConfig()
+ .readTimeout(Duration.ofSeconds(90));
+
+ try (AppiumCommandExecutor executor = new AppiumCommandExecutor(
+ MobileCommand.commandRepository, service, customConfig)) {
+ assertEquals(service.getUrl(), executor.getAddressOfRemoteServer());
+ assertEquals(service.getUrl(), executor.getAppiumClientConfig().baseUrl());
+ assertEquals(Duration.ofSeconds(90), executor.getAppiumClientConfig().readTimeout());
+ }
+ }
+
+ @Test
+ void acceptsNullableLocalServiceWithClientConfig() throws MalformedURLException {
+ URL baseUrl = new URL(APPIUM_URL);
+ try (AppiumCommandExecutor executor = new AppiumCommandExecutor(
+ MobileCommand.commandRepository,
+ (AppiumDriverLocalService) null,
+ AppiumClientConfig.defaultConfig().baseUrl(baseUrl)
+ )) {
+ assertEquals(baseUrl, executor.getAddressOfRemoteServer());
+ }
+ }
+
+ @Test
+ void directConnectSupportsUppercaseProtocolIpv6LiteralAndRelativePath() throws MalformedURLException {
+ String caps = "{\"platformName\":\"Android\",\"appium:automationName\":\"UiAutomator2\","
+ + "\"appium:directConnectProtocol\":\"HTTPS\","
+ + "\"appium:directConnectHost\":\"2001:db8::1\","
+ + "\"appium:directConnectPort\":4443,"
+ + "\"appium:directConnectPath\":\"wd/hub\"}";
+ HttpClient.Factory factory = cfg -> new RecordingHttpClient(cfg, caps);
+ AppiumCommandExecutor executor = new AppiumCommandExecutor(
+ MobileCommand.commandRepository, null, factory,
+ AppiumClientConfig.defaultConfig().baseUrl(new URL(APPIUM_URL)).directConnect(true));
+
+ AndroidDriver driver = new AndroidDriver(executor, new UiAutomator2Options().setDeviceName("emu"));
+ try {
+ URL expected = new URL("https://[2001:db8::1]:4443/wd/hub");
+ assertEquals(expected, executor.getAddressOfRemoteServer());
+ assertEquals(expected, executor.getAppiumClientConfig().baseUrl());
+ assertEquals(expected, driver.getRemoteAddress());
+
+ URL nextOverride = new URL("https://203.0.113.2:4443/wd/hub");
+ executor.overrideServerUrl(nextOverride);
+ assertEquals(nextOverride, driver.getRemoteAddress());
+ } finally {
+ driver.quit();
+ }
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void logBroadcastsUseConnectedServerForDefaultLogcatAndInitialWsSchemeForOverloads()
+ throws MalformedURLException {
+ String androidCaps = "{\"platformName\":\"Android\",\"appium:automationName\":\"UiAutomator2\","
+ + "\"appium:directConnectProtocol\":\"https\","
+ + "\"appium:directConnectHost\":\"203.0.113.1\","
+ + "\"appium:directConnectPort\":4443,"
+ + "\"appium:directConnectPath\":\"/wd/hub\"}";
+ List androidClients = new ArrayList<>();
+ AppiumCommandExecutor androidExecutor = newDirectConnectExecutor(
+ new URL("http://hub.example.com:4723"), androidCaps, androidClients
+ );
+
+ AndroidDriver androidDriver = new AndroidDriver(
+ androidExecutor,
+ new UiAutomator2Options().setDeviceName("emu")
+ );
+ try {
+ assertEquals(new URL("https://203.0.113.1:4443/wd/hub"), androidDriver.getRemoteAddress());
+ androidDriver.startLogcatBroadcast();
+ androidDriver.startLogcatBroadcast("10.0.0.5");
+ androidDriver.startLogcatBroadcast("hub.example.com", 4723);
+
+ assertEquals(
+ List.of(
+ "wss://203.0.113.1:4443/ws/session/s1/appium/device/logcat",
+ "ws://10.0.0.5:4723/ws/session/s1/appium/device/logcat",
+ "ws://hub.example.com:4723/ws/session/s1/appium/device/logcat"
+ ),
+ androidClients.get(1).socketUris
+ );
+ } finally {
+ androidDriver.quit();
+ }
+
+ String iosCaps = "{\"platformName\":\"iOS\",\"appium:automationName\":\"XCUITest\","
+ + "\"appium:directConnectProtocol\":\"https\","
+ + "\"appium:directConnectHost\":\"2001:db8::1\","
+ + "\"appium:directConnectPort\":4443,"
+ + "\"appium:directConnectPath\":\"/wd/hub\"}";
+ List iosClients = new ArrayList<>();
+ AppiumCommandExecutor iosExecutor = newDirectConnectExecutor(
+ new URL("http://hub.example.com:4723"), iosCaps, iosClients
+ );
+
+ IOSDriver iosDriver = new IOSDriver(
+ iosExecutor,
+ new XCUITestOptions().setDeviceName("iPhone 16")
+ );
+ try {
+ assertEquals(new URL("https://[2001:db8::1]:4443/wd/hub"), iosDriver.getRemoteAddress());
+ iosDriver.startSyslogBroadcast();
+ iosDriver.startSyslogBroadcast("log.internal");
+ iosDriver.startSyslogBroadcast("hub.example.com", 4723);
+ iosDriver.startSyslogBroadcast("2001:db8::1", 4443);
+
+ assertEquals(
+ List.of(
+ "ws://localhost:4723/ws/session/s1/appium/device/syslog",
+ "ws://log.internal:4723/ws/session/s1/appium/device/syslog",
+ "ws://hub.example.com:4723/ws/session/s1/appium/device/syslog",
+ "ws://[2001:db8::1]:4443/ws/session/s1/appium/device/syslog"
+ ),
+ iosClients.get(1).socketUris
+ );
+ } finally {
+ iosDriver.quit();
+ }
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void logBroadcastsUseConnectedServerAndInitialWssSchemeWhenInitialServerIsHttps() throws MalformedURLException {
+ String androidCaps = "{\"platformName\":\"Android\",\"appium:automationName\":\"UiAutomator2\","
+ + "\"appium:directConnectProtocol\":\"https\","
+ + "\"appium:directConnectHost\":\"203.0.113.1\","
+ + "\"appium:directConnectPort\":4443,"
+ + "\"appium:directConnectPath\":\"/wd/hub\"}";
+ List androidClients = new ArrayList<>();
+ AppiumCommandExecutor androidExecutor = newDirectConnectExecutor(
+ new URL("https://grid.example.com"), androidCaps, androidClients
+ );
+
+ AndroidDriver androidDriver = new AndroidDriver(
+ androidExecutor,
+ new UiAutomator2Options().setDeviceName("emu")
+ );
+ try {
+ androidDriver.startLogcatBroadcast();
+ androidDriver.startLogcatBroadcast("10.0.0.5");
+ androidDriver.startLogcatBroadcast("10.0.0.5", 443);
+
+ assertEquals(
+ List.of(
+ "wss://203.0.113.1:4443/ws/session/s1/appium/device/logcat",
+ "wss://10.0.0.5:4723/ws/session/s1/appium/device/logcat",
+ "wss://10.0.0.5:443/ws/session/s1/appium/device/logcat"
+ ),
+ androidClients.get(1).socketUris
+ );
+ } finally {
+ androidDriver.quit();
+ }
+
+ String iosCaps = "{\"platformName\":\"iOS\",\"appium:automationName\":\"XCUITest\","
+ + "\"appium:directConnectProtocol\":\"https\","
+ + "\"appium:directConnectHost\":\"2001:db8::1\","
+ + "\"appium:directConnectPort\":4443,"
+ + "\"appium:directConnectPath\":\"/wd/hub\"}";
+ List iosClients = new ArrayList<>();
+ AppiumCommandExecutor iosExecutor = newDirectConnectExecutor(
+ new URL("https://grid.example.com"), iosCaps, iosClients
+ );
+
+ IOSDriver iosDriver = new IOSDriver(
+ iosExecutor,
+ new XCUITestOptions().setDeviceName("iPhone 16")
+ );
+ try {
+ iosDriver.startSyslogBroadcast("2001:db8::1", 4443);
+
+ assertEquals(
+ List.of("wss://[2001:db8::1]:4443/ws/session/s1/appium/device/syslog"),
+ iosClients.get(1).socketUris
+ );
+ } finally {
+ iosDriver.quit();
+ }
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void logBroadcastsHandleNullInitialBaseUrlForDefaultLogcatAndExplicitOverloads()
+ throws MalformedURLException {
+ String androidCaps = "{\"platformName\":\"Android\",\"appium:automationName\":\"UiAutomator2\","
+ + "\"appium:directConnectProtocol\":\"https\","
+ + "\"appium:directConnectHost\":\"203.0.113.1\","
+ + "\"appium:directConnectPort\":4443,"
+ + "\"appium:directConnectPath\":\"/wd/hub\"}";
+ List clients = new ArrayList<>();
+ AppiumCommandExecutor executor = newDirectConnectExecutor(null, androidCaps, clients);
+
+ AndroidDriver driver = new AndroidDriver(
+ executor,
+ new UiAutomator2Options().setDeviceName("emu")
+ );
+ try {
+ assertEquals(new URL("https://203.0.113.1:4443/wd/hub"), driver.getRemoteAddress());
+ driver.startLogcatBroadcast();
+ driver.startLogcatBroadcast("10.0.0.5", 4723);
+ assertEquals(
+ List.of(
+ "wss://203.0.113.1:4443/ws/session/s1/appium/device/logcat",
+ "ws://10.0.0.5:4723/ws/session/s1/appium/device/logcat"
+ ),
+ clients.get(1).socketUris
+ );
+ } finally {
+ driver.quit();
+ }
+
+ List overriddenClients = new ArrayList<>();
+ AppiumCommandExecutor overriddenExecutor = newDirectConnectExecutor(null, androidCaps, overriddenClients);
+ AndroidDriver overriddenDriver = new AndroidDriver(
+ overriddenExecutor,
+ new UiAutomator2Options().setDeviceName("emu")
+ );
+ try {
+ overriddenExecutor.overrideServerUrl(new URL("https://203.0.113.2/wd/hub"));
+ overriddenDriver.startLogcatBroadcast();
+
+ assertEquals(
+ List.of("wss://203.0.113.2/ws/session/s1/appium/device/logcat"),
+ overriddenClients.get(2).socketUris
+ );
+ } finally {
+ overriddenDriver.quit();
+ }
+
+ String iosCaps = "{\"platformName\":\"iOS\",\"appium:automationName\":\"XCUITest\","
+ + "\"appium:directConnectProtocol\":\"https\","
+ + "\"appium:directConnectHost\":\"2001:db8::1\","
+ + "\"appium:directConnectPort\":4443,"
+ + "\"appium:directConnectPath\":\"/wd/hub\"}";
+ List iosClients = new ArrayList<>();
+ AppiumCommandExecutor iosExecutor = newDirectConnectExecutor(null, iosCaps, iosClients);
+
+ IOSDriver iosDriver = new IOSDriver(
+ iosExecutor,
+ new XCUITestOptions().setDeviceName("iPhone 16")
+ );
+ try {
+ iosDriver.startSyslogBroadcast();
+ iosDriver.startSyslogBroadcast("10.0.0.5", 4723);
+
+ assertEquals(
+ List.of(
+ "ws://localhost:4723/ws/session/s1/appium/device/syslog",
+ "ws://10.0.0.5:4723/ws/session/s1/appium/device/syslog"
+ ),
+ iosClients.get(1).socketUris
+ );
+ } finally {
+ iosDriver.quit();
+ }
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void startLogcatBroadcastThrowsWhenRemoteServerAddressIsNull() throws MalformedURLException {
+ RecordingHttpClient client = new RecordingHttpClient(
+ AppiumClientConfig.defaultConfig(),
+ "{\"platformName\":\"Android\",\"appium:automationName\":\"UiAutomator2\"}"
+ );
+ AppiumCommandExecutor executor = new AppiumCommandExecutor(
+ MobileCommand.commandRepository,
+ null,
+ cfg -> client,
+ AppiumClientConfig.defaultConfig().baseUrl(new URL(APPIUM_URL))
+ ) {
+ @Override
+ public @Nullable URL getAddressOfRemoteServer() {
+ return null;
+ }
+ };
+
+ AndroidDriver driver = new AndroidDriver(
+ executor,
+ new UiAutomator2Options().setDeviceName("emu")
+ );
+ try {
+ IllegalArgumentException exception = assertThrows(
+ IllegalArgumentException.class,
+ driver::startLogcatBroadcast
+ );
+ assertEquals("The Appium server address is not set", exception.getMessage());
+ assertTrue(client.socketUris.isEmpty());
+ } finally {
+ driver.quit();
+ }
+ }
+
+ private static AppiumCommandExecutor newDirectConnectExecutor(
+ @Nullable URL initialBaseUrl,
+ String caps,
+ List clients
+ ) {
+ HttpClient.Factory factory = cfg -> {
+ RecordingHttpClient client = new RecordingHttpClient(cfg, caps);
+ clients.add(client);
+ return client;
+ };
+ AppiumClientConfig config = AppiumClientConfig.defaultConfig().directConnect(true);
+ if (initialBaseUrl != null) {
+ config = config.baseUrl(initialBaseUrl);
+ }
+ return new AppiumCommandExecutor(MobileCommand.commandRepository, null, factory, config);
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void initialServerUrlPreservesOriginalValueAcrossOverridesAndNullBaseUri() throws MalformedURLException {
+ HttpClient.Factory factory = cfg -> new RecordingHttpClient(cfg, "{\"platformName\":\"Android\"}");
+ URL initialUrl = new URL("http://hub.example.com:4723");
+ AppiumCommandExecutor executor = new AppiumCommandExecutor(
+ MobileCommand.commandRepository,
+ null,
+ factory,
+ AppiumClientConfig.defaultConfig().baseUrl(initialUrl)
+ );
+ assertEquals(initialUrl, CommandExecutorInternals.getInitialServerUrl(executor));
+
+ URL firstOverride = new URL("https://203.0.113.1:4443/wd/hub");
+ URL secondOverride = new URL("https://203.0.113.2:4443/wd/hub");
+ executor.overrideServerUrl(firstOverride);
+ executor.overrideServerUrl(secondOverride);
+ assertEquals(secondOverride, executor.getAddressOfRemoteServer());
+ assertEquals(initialUrl, CommandExecutorInternals.getInitialServerUrl(executor));
+
+ AppiumCommandExecutor nullBaseExecutor = new AppiumCommandExecutor(
+ MobileCommand.commandRepository,
+ null,
+ factory,
+ AppiumClientConfig.defaultConfig()
+ );
+ assertNull(CommandExecutorInternals.getInitialServerUrl(nullBaseExecutor));
+ nullBaseExecutor.overrideServerUrl(firstOverride);
+ assertEquals(firstOverride, nullBaseExecutor.getAddressOfRemoteServer());
+ assertNull(CommandExecutorInternals.getInitialServerUrl(nullBaseExecutor));
+
+ URL customUrl = new URL("https://custom.example.com:8443");
+ AppiumCommandExecutor subclassExecutor = new AppiumCommandExecutor(
+ MobileCommand.commandRepository,
+ null,
+ factory,
+ AppiumClientConfig.defaultConfig().baseUrl(initialUrl)
+ ) {
+ @Override
+ public URL getAddressOfRemoteServer() {
+ return customUrl;
+ }
+ };
+ assertEquals(customUrl, CommandExecutorInternals.getInitialServerUrl(subclassExecutor));
+
+ assertThrows(
+ SecurityException.class,
+ () -> CommandExecutorInternals.registerInitialServerUrlResolver(
+ MethodHandles.lookup(),
+ AppiumCommandExecutor::getAddressOfRemoteServer
+ )
+ );
+ }
+
+ @Test
+ void blankDirectConnectValuesFailWithSessionNotCreatedException() throws MalformedURLException {
+ for (String invalidCaps : List.of(
+ "{\"platformName\":\"Android\","
+ + "\"appium:directConnectProtocol\":\"https\","
+ + "\"appium:directConnectHost\":\"x\","
+ + "\"appium:directConnectPort\":\"\","
+ + "\"appium:directConnectPath\":\"/wd/hub\"}",
+ "{\"platformName\":\"Android\","
+ + "\"appium:directConnectProtocol\":\"\","
+ + "\"appium:directConnectHost\":\"\","
+ + "\"appium:directConnectPort\":\"\","
+ + "\"appium:directConnectPath\":\"\"}")) {
+ HttpClient.Factory factory = cfg -> new RecordingHttpClient(cfg, invalidCaps);
+ AppiumCommandExecutor executor = new AppiumCommandExecutor(
+ MobileCommand.commandRepository,
+ null,
+ factory,
+ AppiumClientConfig.defaultConfig()
+ .baseUrl(new URL("http://hub.example.com:4723"))
+ .directConnect(true)
+ );
+
+ assertThrows(
+ SessionNotCreatedException.class,
+ () -> new AndroidDriver(executor, new UiAutomator2Options().setDeviceName("emu"))
+ );
+ }
}
}
diff --git a/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java b/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java
index a8542460b..9ed100e8c 100644
--- a/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java
+++ b/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java
@@ -56,6 +56,8 @@
import java.util.function.Function;
import java.util.regex.Pattern;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Pins the HTTP requests a driver sends for each WebDriver/Appium API call, and what it returns
* for scripted server responses. Set GOLDEN_UPDATE=1 to regenerate the golden file.
@@ -593,6 +595,9 @@ void directConnect() {
Map described = new LinkedHashMap<>();
try {
var driver = newDriver(transport, AppiumClientConfig.defaultConfig().directConnect(true));
+ if ("valid".equals(name)) {
+ assertEquals("https://203.0.113.1:4443/wd/hub", driver.getRemoteAddress().toString());
+ }
transport.requests.clear();
driver.getTitle();
} catch (Throwable t) {