Skip to content
Open
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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();
}
}
}
16 changes: 11 additions & 5 deletions src/main/java/io/appium/java_client/AppiumDriver.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

/**
Expand All @@ -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();
}

/**
Expand Down Expand Up @@ -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() {
Comment thread
mykola-mokhnach marked this conversation as resolved.
Resolved
return ((AppiumCommandExecutor) getCommandExecutor()).getAddressOfRemoteServer();
}

@Override
public ExecuteMethod getExecuteMethod() {
return executeMethod;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
*/
Expand All @@ -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
Expand All @@ -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");
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -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
* <a href="https://github.com/appium/java-client/blob/master/docs/selenium-bridge.md#bidi">Selenium
* bridge documentation</a>.
*/
@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<StringWebSocketClient> 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<StringWebSocketClient> clientSupplier,
String host,
int port,
String deviceLogType
) {
var remoteWebDriver = (AppiumRemoteWebDriver) driver;
var executor = (AppiumCommandExecutor) remoteWebDriver.getCommandExecutor();
startBroadcast(
remoteWebDriver,
driver,
clientSupplier,
executor.getInitialServerUrl(),
host,
port,
deviceLogType
);
}

private static void startBroadcast(
AppiumRemoteWebDriver remoteWebDriver,
ExecutesMethod driver,
Supplier<StringWebSocketClient> 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);
}
}
}
16 changes: 16 additions & 0 deletions src/main/java/io/appium/java_client/internal/Strings.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Loading
Loading