0
# Driver Services
1
2
Management of native driver executables including automatic discovery, lifecycle control, and process communication. This system handles the complexity of starting, stopping, and communicating with browser driver processes like ChromeDriver, GeckoDriver, and EdgeDriver.
3
4
## Capabilities
5
6
### DriverService
7
8
Abstract base class for managing native WebDriver executables, providing lifecycle management and process communication.
9
10
```java { .api }
11
/**
12
* Abstract base class for managing native driver executables
13
*/
14
public abstract class DriverService implements Closeable {
15
16
// Constants for log output destinations
17
public static final String LOG_NULL = "/dev/null";
18
public static final String LOG_STDERR = "/dev/stderr";
19
public static final String LOG_STDOUT = "/dev/stdout";
20
21
// Abstract methods - implemented by specific driver services
22
public abstract String getExecutable();
23
public abstract URL getUrl();
24
25
// Lifecycle management
26
public void start() throws IOException;
27
public void stop();
28
public void close();
29
public boolean isRunning();
30
31
// Process communication
32
public void sendOutputTo(OutputStream outputStream) throws IOException;
33
34
// Configuration
35
public void setExecutable(String executable);
36
37
/**
38
* Abstract builder base class for driver services
39
*/
40
public static abstract class Builder<DS extends DriverService, B extends Builder<?, ?>> {
41
42
// Common configuration methods
43
public B usingDriverExecutable(File file);
44
public B usingAnyFreePort();
45
public B usingPort(int port);
46
public B withEnvironment(Map<String, String> environment);
47
public B withLogFile(File logFile);
48
public B withLogOutput(OutputStream logOutput);
49
public B withSilent(boolean silent);
50
public B withVerbose(boolean verbose);
51
52
// Build method - returns specific driver service
53
public abstract DS build();
54
}
55
}
56
```
57
58
**Usage Examples:**
59
60
```java
61
// Example with a hypothetical ChromeDriverService
62
ChromeDriverService service = new ChromeDriverService.Builder()
63
.usingDriverExecutable(new File("/usr/local/bin/chromedriver"))
64
.usingPort(9515)
65
.withLogFile(new File("/tmp/chromedriver.log"))
66
.withVerbose(true)
67
.build();
68
69
// Start the service
70
service.start();
71
URL serviceUrl = service.getUrl(); // http://localhost:9515
72
73
// Check if running
74
boolean running = service.isRunning();
75
76
// Stop the service
77
service.stop();
78
```
79
80
### DriverCommandExecutor
81
82
Command executor that manages a driver service, automatically starting and stopping the service as needed.
83
84
```java { .api }
85
/**
86
* Command executor that manages a driver service lifecycle
87
*/
88
public class DriverCommandExecutor implements CommandExecutor {
89
90
// Constructors
91
public DriverCommandExecutor(DriverService service);
92
public DriverCommandExecutor(DriverService service,
93
Map<String, CommandInfo> additionalCommands);
94
95
// Command execution
96
public Response execute(Command command) throws IOException;
97
}
98
```
99
100
**Usage Examples:**
101
102
```java
103
import org.openqa.selenium.remote.service.DriverCommandExecutor;
104
import org.openqa.selenium.remote.RemoteWebDriver;
105
106
// Create driver service
107
ChromeDriverService service = new ChromeDriverService.Builder()
108
.usingAnyFreePort()
109
.build();
110
111
// Create command executor with service management
112
DriverCommandExecutor executor = new DriverCommandExecutor(service);
113
114
// Use with RemoteWebDriver - service will be started automatically
115
RemoteWebDriver driver = new RemoteWebDriver(executor, capabilities);
116
117
// Service is automatically stopped when driver quits
118
driver.quit();
119
```
120
121
### DriverFinder
122
123
Utility for finding and locating driver executables on the system, with support for automatic driver management.
124
125
```java { .api }
126
/**
127
* Utility for finding driver executables
128
*/
129
public class DriverFinder {
130
131
/**
132
* Find driver executable for the given builder and capabilities
133
* @param builder Driver service builder
134
* @param capabilities Browser capabilities
135
* @return Result containing driver information
136
*/
137
public static Result getResult(DriverService.Builder<?, ?> builder,
138
Capabilities capabilities);
139
140
/**
141
* Result of driver finding operation
142
*/
143
public static class Result {
144
public String getDriverPath();
145
public String getBrowserPath();
146
public String getDriverVersion();
147
public String getBrowserVersion();
148
}
149
}
150
```
151
152
**Usage Examples:**
153
154
```java
155
import org.openqa.selenium.remote.service.DriverFinder;
156
import org.openqa.selenium.chrome.ChromeOptions;
157
158
// Find Chrome driver automatically
159
ChromeOptions options = new ChromeOptions();
160
ChromeDriverService.Builder builder = new ChromeDriverService.Builder();
161
162
DriverFinder.Result result = DriverFinder.getResult(builder, options);
163
String driverPath = result.getDriverPath();
164
String browserPath = result.getBrowserPath();
165
String driverVersion = result.getDriverVersion();
166
167
// Use found driver
168
ChromeDriverService service = builder
169
.usingDriverExecutable(new File(driverPath))
170
.build();
171
```
172
173
## Driver Service Patterns
174
175
### Service Builder Pattern
176
177
All driver services follow a consistent builder pattern for configuration:
178
179
```java
180
// Generic pattern for all driver services
181
SpecificDriverService service = new SpecificDriverService.Builder()
182
.usingDriverExecutable(new File("/path/to/driver"))
183
.usingPort(specificPort)
184
.withEnvironment(environmentVariables)
185
.withLogFile(new File("/path/to/log"))
186
.withVerbose(true)
187
.build();
188
```
189
190
### Service Lifecycle Management
191
192
```java
193
// Manual lifecycle management
194
service.start();
195
try {
196
// Use service
197
RemoteWebDriver driver = new RemoteWebDriver(service.getUrl(), capabilities);
198
// ... perform operations
199
driver.quit();
200
} finally {
201
service.stop();
202
}
203
204
// Automatic lifecycle management with try-with-resources
205
try (DriverService service = builder.build()) {
206
service.start();
207
RemoteWebDriver driver = new RemoteWebDriver(service.getUrl(), capabilities);
208
// Service automatically stopped when try block exits
209
}
210
```
211
212
### Service Configuration Options
213
214
Common configuration patterns across all driver services:
215
216
```java
217
// Port configuration
218
.usingAnyFreePort() // Let system choose free port
219
.usingPort(9515) // Specific port
220
221
// Executable configuration
222
.usingDriverExecutable(file) // Specific executable path
223
224
// Logging configuration
225
.withLogFile(file) // Log to file
226
.withLogOutput(outputStream) // Log to stream
227
.withSilent(true) // Suppress output
228
.withVerbose(true) // Verbose logging
229
230
// Environment configuration
231
.withEnvironment(envMap) // Custom environment variables
232
```
233
234
### Integration with RemoteWebDriver
235
236
Driver services integrate seamlessly with RemoteWebDriver in multiple ways:
237
238
```java
239
// Direct URL usage
240
DriverService service = builder.build();
241
service.start();
242
RemoteWebDriver driver = new RemoteWebDriver(service.getUrl(), capabilities);
243
244
// Command executor usage (recommended)
245
DriverCommandExecutor executor = new DriverCommandExecutor(service);
246
RemoteWebDriver driver = new RemoteWebDriver(executor, capabilities);
247
248
// Builder integration (Beta)
249
RemoteWebDriver driver = RemoteWebDriver.builder()
250
.withDriverService(service)
251
.addAlternative(capabilities)
252
.build();
253
```
254
255
### Error Handling and Diagnostics
256
257
```java
258
try {
259
service.start();
260
} catch (IOException e) {
261
// Handle service startup failure
262
System.err.println("Failed to start driver service: " + e.getMessage());
263
264
// Check if executable exists
265
File executable = new File(service.getExecutable());
266
if (!executable.exists()) {
267
System.err.println("Driver executable not found: " + executable.getPath());
268
}
269
270
// Check if port is available
271
if (!isPortAvailable(service.getUrl().getPort())) {
272
System.err.println("Port already in use: " + service.getUrl().getPort());
273
}
274
}
275
276
// Monitor service health
277
if (service.isRunning()) {
278
System.out.println("Service running at: " + service.getUrl());
279
} else {
280
System.err.println("Service failed to start or has stopped");
281
}
282
```
283
284
### Advanced Service Configuration
285
286
```java
287
// Custom environment variables for driver
288
Map<String, String> environment = new HashMap<>();
289
environment.put("DISPLAY", ":99"); // For headless environments
290
environment.put("PATH", customPath); // Custom PATH
291
292
// Service with custom configuration
293
DriverService service = new SpecificDriverService.Builder()
294
.withEnvironment(environment)
295
.withLogOutput(new FileOutputStream("/var/log/driver.log"))
296
.usingDriverExecutable(findDriverExecutable())
297
.build();
298
299
// Redirect output for debugging
300
ByteArrayOutputStream logCapture = new ByteArrayOutputStream();
301
service.sendOutputTo(logCapture);
302
service.start();
303
304
// Later, examine captured logs
305
String driverLogs = logCapture.toString();
306
```
307
308
### Service Health Monitoring
309
310
```java
311
// Monitor service status
312
public boolean isServiceHealthy(DriverService service) {
313
if (!service.isRunning()) {
314
return false;
315
}
316
317
try {
318
// Send simple HTTP request to service
319
HttpClient client = HttpClient.createDefault().createClient(
320
ClientConfig.defaultConfig().baseUrl(service.getUrl()));
321
HttpRequest request = new HttpRequest(HttpMethod.GET, "/status");
322
HttpResponse response = client.execute(request);
323
return response.getStatus() == 200;
324
} catch (Exception e) {
325
return false;
326
}
327
}
328
329
// Restart service if unhealthy
330
if (!isServiceHealthy(service)) {
331
service.stop();
332
service.start();
333
}
334
```