Skip to content

Add wrappers for Android logcat broadcaster #858

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 13, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ dependencies {
force = true
}
compile 'com.google.code.gson:gson:2.8.2'
compile 'javax.websocket:javax.websocket-api:1.1'
compile 'org.apache.httpcomponents:httpclient:4.5.5'
compile 'cglib:cglib:3.2.6'
compile 'commons-validator:commons-validator:1.6'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public class AndroidDriver<T extends WebElement>
FindsByAndroidUIAutomator<T>, LocksDevice, HasAndroidSettings, HasDeviceDetails,
HasSupportedPerformanceDataType, AuthenticatesByFinger,
CanRecordScreen, SupportsSpecialEmulatorCommands,
SupportsNetworkStateManagement {
SupportsNetworkStateManagement, ListensToLogcatMessages {

private static final String ANDROID_PLATFORM = MobilePlatform.ANDROID;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package io.appium.java_client.android;

import static io.appium.java_client.service.local.AppiumServiceBuilder.DEFAULT_APPIUM_PORT;
import static org.openqa.selenium.remote.DriverCommand.EXECUTE_SCRIPT;

import com.google.common.collect.ImmutableMap;

import io.appium.java_client.ExecutesMethod;
import io.appium.java_client.ws.StringMessagesHandler;
import io.appium.java_client.ws.StringWebSocketClient;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.URI;
import java.net.URISyntaxException;

public interface ListensToLogcatMessages extends ExecutesMethod {
StringWebSocketClient logcatClient = new StringWebSocketClient();

/**
* Start logcat messages broadcast via web socket.
* This method assumes that Appium server is running on localhost and
* is assigned to the default port (4723).
*/
default void startLogcatBroadcast() {
startLogcatBroadcast("localhost", DEFAULT_APPIUM_PORT);
}

/**
* Start logcat messages broadcast via web socket.
*
* @param host the name of the host where Appium server is running
* @param port the port of the host where Appium server is running
*/
default void startLogcatBroadcast(String host, int port) {
execute(EXECUTE_SCRIPT, ImmutableMap.of("script", "mobile: startLogsBroadcast"));
final URI endpointUri;
try {
endpointUri = new URI(String.format("ws://%s:%s/ws/session/%s/appium/device/logcat",
host, port, ((RemoteWebDriver) this).getSessionId()));
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
logcatClient.connect(endpointUri);
}

/**
* Adds a new log broadcasting handler.
* Several handlers might be assigned to a single server.
* Multiple calls to this method will cause the handler
* to be called multiple times.
*
* @param handler an instance of a class, which implement string message handlers
*/
default void addLogcatListener(StringMessagesHandler handler) {
logcatClient.addMessageHandler(handler);
}

/**
* Removes all existing logcat message handlers.
*/
default void removeAllLogcatListeners() {
logcatClient.removeAllMessageHandlers();
}

/**
* Stops logcat messages broadcast via web socket.
*/
default void stopLogcatBroadcast() {
execute(EXECUTE_SCRIPT, ImmutableMap.of("script", "mobile: stopLogsBroadcast"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public final class AppiumServiceBuilder
File.separator + BUILD_FOLDER
+ File.separator + LIB_FOLDER
+ File.separator + MAIN_JS;
private static final int DEFAULT_APPIUM_PORT = 4723;
public static final int DEFAULT_APPIUM_PORT = 4723;
private static final String BASH = "bash";
private static final String CMD_EXE = "cmd.exe";
private static final String NODE = "node";
Expand Down
49 changes: 49 additions & 0 deletions src/main/java/io/appium/java_client/ws/CanHandleMessages.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package io.appium.java_client.ws;

import java.util.List;

/**
* This interface might be assigned to classes, which
* are defined as web socket clients.
*/
public interface CanHandleMessages<T extends MessagesHandler> {
/**
* @return The list of web socket message handlers.
*/
List<T> messageHandlers();
Copy link

Choose a reason for hiding this comment

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

messageHandlers() -> getMessageHandlers()


/**
* Register a new message handler.
*
* @param msgHandler an instance of a class, which
* implements MessagesHandler interface
*/
default void addMessageHandler(T msgHandler) {
messageHandlers().add(msgHandler);
}

/**
* Removes an existing message handler.
*
* @param msgHandler an instance of a class, which
* implements MessagesHandler interface
* @return true if the given class instance was registered before and has been successfully removed.
*/
default boolean removeMessageHandler(T msgHandler) {
return messageHandlers().remove(msgHandler);
}

/**
* @return The count of registered message handlers.
*/
default int messageHandlersCount() {
return messageHandlers().size();
}

/**
* Removes all registered message handlers.
*/
default void removeAllMessageHandlers() {
messageHandlers().clear();
}
}
28 changes: 28 additions & 0 deletions src/main/java/io/appium/java_client/ws/MessagesHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package io.appium.java_client.ws;

/**
* This is the basic interface for all web socket message handlers.
*/
public interface MessagesHandler {
Copy link

Choose a reason for hiding this comment

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

It's strange that messages handler can not handle messages.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yep, I'll make it generic

/**
* This event is fired when the client is
* successfully connected to a web socket.
*/
void onConnected();

/**
* This event is fired when the client is
* disconnected from a web socket.
*/
void onDisconnected();

/**
* This event is fired when there is an error
* in the web socket connection.
* onDisconnected event is always generated after
* onError happens.
*
* @param reason the actual error reason.
*/
void onError(Throwable reason);
}
15 changes: 15 additions & 0 deletions src/main/java/io/appium/java_client/ws/StringMessagesHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package io.appium.java_client.ws;

/**
* All classes, that handle web socket messages of String type
* must implement this interface.
*/
public interface StringMessagesHandler extends MessagesHandler {
/**
* This event is fired when the client receives
* a new string message from a web socket.
*
* @param message the actual message content
*/
void onMessage(String message);
}
100 changes: 100 additions & 0 deletions src/main/java/io/appium/java_client/ws/StringWebSocketClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package io.appium.java_client.ws;

import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;

@ClientEndpoint
public class StringWebSocketClient extends WebSocketClient
implements CanHandleMessages<StringMessagesHandler> {
private final List<StringMessagesHandler> messageHandlers = new CopyOnWriteArrayList<>();
private volatile Session session;

@Override
public void connect(URI endpoint) {
if (session != null) {
if (endpoint.equals(this.getEndpoint())) {
return;
}
removeAllMessageHandlers();
try {
session.close();
} catch (IOException e) {
// ignore
}
session = null;
}
super.connect(endpoint);
}

/**
* This event if fired when the client is successfully
* connected to a web socket.
*
* @param session the actual web socket session instance
* @param config endpoint config
*/
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
this.session = session;
messageHandlers().forEach(MessagesHandler::onConnected);
}

/**
* This event if fired when the client is
* disconnected from a web socket.
*
* @param session the actual web socket session instance
* @param reason connection close reason
*/
@OnClose
public void onClose(Session session, CloseReason reason) {
Copy link

Choose a reason for hiding this comment

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

session parameter is never used.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

it is used in connect

Copy link

Choose a reason for hiding this comment

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

@OnClose
public void onClose(CloseReason reason) {

this.session = null;
messageHandlers().forEach(MessagesHandler::onDisconnected);
}

/**
* This event if fired when there is an unexpected
* error in web socket connection.
*
* @param session the actual web socket session instance
* @param reason the actual error reason
*/
@OnError
public void onError(Session session, Throwable reason) {
this.session = null;
messageHandlers().forEach(x -> {
x.onError(reason);
x.onDisconnected();
});
throw new RuntimeException(reason);
}

/**
* This event if fired when there is a
* new message from the web socket.
*
* @param message the actual message content.
*/
@OnMessage
public void onMessage(String message) {
messageHandlers().forEach(x -> x.onMessage(message));
}

/**
* @return The list of all registered web socket messages handlers.
*/
@Override
public List<StringMessagesHandler> messageHandlers() {
return messageHandlers;
}
}
37 changes: 37 additions & 0 deletions src/main/java/io/appium/java_client/ws/WebSocketClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package io.appium.java_client.ws;

import org.openqa.selenium.WebDriverException;

import java.io.IOException;
import java.net.URI;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;

public abstract class WebSocketClient {
private URI endpoint;

private void setEndpoint(URI endpoint) {
this.endpoint = endpoint;
}

public URI getEndpoint() {
return this.endpoint;
}

/**
* Connects web socket client.
*
* @param endpoint The full address of an endpoint to connect to.
* Usually starts with 'ws://'.
*/
public void connect(URI endpoint) {
try {
ContainerProvider
.getWebSocketContainer()
.connectToServer(this, endpoint);
setEndpoint(endpoint);
} catch (IOException | DeploymentException e) {
throw new WebDriverException(e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package io.appium.java_client.android;

import static org.junit.Assert.assertTrue;

import io.appium.java_client.ws.StringMessagesHandler;
import org.junit.Test;

import java.time.Duration;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class AndroidLogcatListenerTest extends BaseAndroidTest {

@Test
public void verifyLogcatListenerCanBeAssigned() {
final Semaphore messageSemaphore = new Semaphore(1);
final Semaphore connectedSemaphore = new Semaphore(1);
final Duration timeout = Duration.ofSeconds(5);

try {
driver.startLogcatBroadcast();
driver.addLogcatListener(new StringMessagesHandler() {
@Override
public void onMessage(String message) {
messageSemaphore.release();
}

@Override
public void onConnected() {
connectedSemaphore.release();
}

@Override
public void onDisconnected() {
// ignore
}

@Override
public void onError(Throwable reason) {
// ignore
}
});

connectedSemaphore.acquire();
messageSemaphore.acquire();

assertTrue(String.format("Didn't connect to the web socket after %s timeout", timeout),
connectedSemaphore.tryAcquire(timeout.toMillis(), TimeUnit.MILLISECONDS));
assertTrue(String.format("Didn't receive any log message after %s timeout", timeout),
messageSemaphore.tryAcquire(timeout.toMillis(), TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
connectedSemaphore.release();
messageSemaphore.release();
driver.stopLogcatBroadcast();
}
}
}