-
-
Notifications
You must be signed in to change notification settings - Fork 8k
/
DevTools.java
161 lines (136 loc) · 5.56 KB
/
DevTools.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. 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 org.openqa.selenium.devtools;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.idealized.Domains;
import org.openqa.selenium.devtools.idealized.target.model.SessionID;
import org.openqa.selenium.devtools.idealized.target.model.TargetID;
import org.openqa.selenium.devtools.idealized.target.model.TargetInfo;
import org.openqa.selenium.internal.Require;
import java.io.Closeable;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class DevTools implements Closeable {
private static final Logger log = Logger.getLogger(DevTools.class.getName());
private final Domains protocol;
private final Duration timeout = Duration.ofSeconds(10);
private final Connection connection;
private SessionID cdpSession = null;
public DevTools(Function<DevTools, Domains> protocol, Connection connection) {
this.connection = Require.nonNull("WebSocket connection", connection);
this.protocol = Require.nonNull("CDP protocol", protocol).apply(this);
}
public Domains getDomains() {
return protocol;
}
@Override
public void close() {
disconnectSession();
}
public void disconnectSession() {
if (cdpSession != null) {
SessionID id = cdpSession;
cdpSession = null;
connection.sendAndWait(
cdpSession, getDomains().target().detachFromTarget(Optional.of(id), Optional.empty()), timeout);
}
}
public <X> X send(Command<X> command) {
Require.nonNull("Command to send", command);
return connection.sendAndWait(cdpSession, command, timeout);
}
public <X> void addListener(Event<X> event, Consumer<X> handler) {
Require.nonNull("Event to listen for", event);
Require.nonNull("Handler to call", handler);
connection.addListener(event, handler);
}
public void clearListeners() {
// By removing all the listeners, we should also disable all the domains
getDomains().disableAll();
connection.clearListeners();
}
public void createSessionIfThereIsNotOne() {
createSessionIfThereIsNotOne(null);
}
public void createSessionIfThereIsNotOne(String windowHandle) {
if (cdpSession == null) {
createSession(windowHandle);
}
}
public void createSession() {
createSession(null);
}
/**
* Create CDP session on given window/tab (aka target).
* If windowHandle is null, then _some_ target will be selected. It might be a problem only if you have multiple windows/tabs opened.
*
* @param windowHandle result of {@link WebDriver#getWindowHandle()}, optional.
*/
public void createSession(String windowHandle) {
TargetID targetId = findTarget(windowHandle);
// Start the session.
cdpSession = connection
.sendAndWait(cdpSession, getDomains().target().attachToTarget(targetId), timeout);
try {
// We can do all of these in parallel, and we don't care about the result.
CompletableFuture.allOf(
// Set auto-attach to true and run for the hills.
connection.send(cdpSession, getDomains().target().setAutoAttach()),
// Clear the existing logs
connection.send(cdpSession, getDomains().log().clear())
.exceptionally(t -> {
log.log(Level.SEVERE, t.getMessage(), t);
return null;
})
).get(timeout.toMillis(), MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Thread has been interrupted", e);
} catch (ExecutionException e) {
throw new DevToolsException(unwrapCause(e));
} catch (TimeoutException e) {
throw new org.openqa.selenium.TimeoutException(e);
}
}
private TargetID findTarget(String windowHandle) {
// Figure out the targets.
List<TargetInfo> infos = connection.sendAndWait(cdpSession, getDomains().target().getTargets(), timeout);
// Grab the first "page" type, and glom on to that.
// Find out which one might be the current one (using given window handle like "CDwindow-24426957AC62D8BC83E58C184C38AF2D")
return infos.stream()
.filter(info -> "page".equals(info.getType()))
.map(TargetInfo::getTargetId)
.filter(id -> windowHandle == null || windowHandle.contains(id.toString()))
.findAny()
.orElseThrow(() -> new DevToolsException("Unable to find target id of a page"));
}
private Throwable unwrapCause(ExecutionException e) {
return e.getCause() != null ? e.getCause() : e;
}
public SessionID getCdpSession() {
return cdpSession;
}
}