Skip to content

Commit f5ee595

Browse files
Improvement with optional
1 parent 12cb9d9 commit f5ee595

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
package io.appium.java_client.remote;
1818

1919
import static com.google.common.base.Throwables.throwIfUnchecked;
20+
import static java.util.Optional.ofNullable;
2021

22+
import com.google.common.base.Function;
2123
import com.google.common.base.Throwables;
2224

2325
import org.openqa.selenium.WebDriverException;
@@ -61,25 +63,30 @@ public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
6163
this(additionalCommands, service, new ApacheHttpClient.Factory());
6264
}
6365

64-
@Override public Response execute(Command command) throws IOException, WebDriverException {
65-
if (DriverCommand.NEW_SESSION.equals(command.getName()) && service != null) {
66-
service.start();
66+
@Override public Response execute(Command command) throws WebDriverException {
67+
if (DriverCommand.NEW_SESSION.equals(command.getName())) {
68+
ofNullable(service).ifPresent(driverService -> {
69+
try {
70+
driverService.start();
71+
} catch (IOException e) {
72+
throw new WebDriverException(e.getMessage(), e);
73+
}
74+
});
6775
}
6876

6977
try {
7078
return super.execute(command);
7179
} catch (Throwable t) {
7280
Throwable rootCause = Throwables.getRootCause(t);
7381
if (rootCause instanceof ConnectException
74-
&& rootCause.getMessage().contains("Connection refused")
75-
&& service != null) {
76-
if (service.isRunning()) {
77-
throw new WebDriverException("The session is closed!", t);
78-
}
82+
&& rootCause.getMessage().contains("Connection refused")) {
83+
throw ofNullable(service).map((Function<DriverService, WebDriverException>) service -> {
84+
if (service.isRunning()) {
85+
return new WebDriverException("The session is closed!", rootCause);
86+
}
7987

80-
if (!service.isRunning()) {
81-
throw new WebDriverException("The appium server has accidentally died!", t);
82-
}
88+
return new WebDriverException("The appium server has accidentally died!", rootCause);
89+
}).orElse(new WebDriverException(rootCause.getMessage(), rootCause));
8390
}
8491
throwIfUnchecked(t);
8592
throw new WebDriverException(t);

0 commit comments

Comments
 (0)