Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,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;
Expand Down Expand Up @@ -64,13 +60,7 @@ default void startLogcatBroadcast(String host) {
* @param port the port of the host where Appium server is running
*/
default void startLogcatBroadcast(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/logcat", scheme, host, port, sessionId);
getLogcatClient().connect(URI.create(endpoint));
LogBroadcastEndpoints.startBroadcast(this, this::getLogcatClient, host, port, "logcat");
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* 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.
*/
@NullMarked
public final class CommandExecutorInternals {
private static final AtomicReference<@Nullable Function<AppiumCommandExecutor, @Nullable URL>>
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}
*/
public static void registerInitialServerUrlResolver(
MethodHandles.Lookup lookup,
Function<AppiumCommandExecutor, @Nullable URL> 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
public static URL getInitialServerUrl(AppiumCommandExecutor executor) {
requireNonNull(executor, "Command executor");
Function<AppiumCommandExecutor, @Nullable URL> resolver = INITIAL_SERVER_URL_RESOLVER.get();
return resolver != null ? resolver.apply(executor) : executor.getAddressOfRemoteServer();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* 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.URL;
import java.util.function.Supplier;

/**
* Shared endpoint resolution and WebSocket startup helpers for device log broadcast listeners.
*/
@NullMarked
@SuppressWarnings("removal")
public final class LogBroadcastEndpoints {
private LogBroadcastEndpoints() {
}

/**
* 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
* @param deviceLogType the log endpoint suffix (such as {@code logcat} or {@code syslog})
*/
public static void startBroadcast(
ExecutesMethod driver,
Supplier<StringWebSocketClient> clientSupplier,
String host,
int port,
String deviceLogType
) {
var remoteWebDriver = (AppiumRemoteWebDriver) driver;
var executor = (AppiumCommandExecutor) remoteWebDriver.getCommandExecutor();
CommandExecutionHelper.executeScript(driver, "mobile: startLogsBroadcast");
URI endpoint = buildBroadcastUri(
CommandExecutorInternals.getInitialServerUrl(executor),
host,
port,
remoteWebDriver.getSessionId(),
deviceLogType
);
clientSupplier.get().connect(endpoint);
}

/**
* Builds a device log broadcast WebSocket URI using {@code wss} when {@code serverUrl} uses
* {@code https}, 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
* @param port the target WebSocket 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
*/
public static URI buildBroadcastUri(
@Nullable URL serverUrl,
String host,
int port,
@Nullable SessionId sessionId,
String deviceLogType
) {
String scheme = serverUrl != null && "https".equalsIgnoreCase(serverUrl.getProtocol()) ? "wss" : "ws";

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Restoring the host and port defaults still leaves a compatibility issue here. Suppose the session starts at http://hub:4723, direct-connects to an HTTPS node, and the caller uses startLogcatBroadcast("hub", 4723) to reach the original plain-WS endpoint. Before this PR that call opened ws://hub:4723/.... This line now selects wss://hub:4723/..., so the TLS handshake fails. The same applies to syslog. Could the existing overloads retain the original scheme and have a regression test for this case? If the change is intentional, please document the compatibility impact and how callers can still select ws.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks! Updated LogBroadcastEndpoints to pick the WebSocket scheme from the executor's initial server URL (before any directConnect or URL override) via an internal bridge so AppiumCommandExecutor does not add new public API.

Sessions starting on plain HTTP now stay on ws for both logcat and syslog broadcasts after direct-connecting to HTTPS, while initial HTTPS sessions keep using wss. Added regression tests covering both cases plus null initial base URL in AppiumCommandExecutorTest.

String endpoint = scheme + "://" + Strings.formatHost(host) + ":" + port
+ "/ws/session/" + sessionId + "/appium/device/" + deviceLogType;
return URI.create(endpoint);
}
}
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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -65,13 +61,7 @@ default void startSyslogBroadcast(String host) {
* @param port the port of the host where Appium server is running
*/
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");
}

/**
Expand Down
Loading
Loading