Skip to content

Commit 9095d3d

Browse files
author
Mykola Mokhnach
authored
Set retry flag to true by default for OkHttpFactory (#928)
* Set retry flag to true by default for OkHttpFactory * Make methods protected * fix private fields setter * Delete extra space * make utility methods protected * Make linter happy
1 parent a56a9a3 commit 9095d3d

File tree

2 files changed

+133
-21
lines changed

2 files changed

+133
-21
lines changed

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

Lines changed: 34 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -89,53 +89,66 @@ public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
8989

9090
public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
9191
URL addressOfRemoteServer) {
92-
this(additionalCommands, addressOfRemoteServer, HttpClient.Factory.createDefault());
92+
this(additionalCommands, addressOfRemoteServer, new AppiumHttpClientFactory());
9393
}
9494

9595
public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
9696
DriverService service) {
97-
this(additionalCommands, service, HttpClient.Factory.createDefault());
97+
this(additionalCommands, service, new AppiumHttpClientFactory());
9898
}
9999

100-
private <B> B getPrivateFieldValue(String fieldName, Class<B> fieldType) {
101-
try {
102-
final Field f = getClass().getSuperclass().getDeclaredField(fieldName);
103-
f.setAccessible(true);
104-
return fieldType.cast(f.get(this));
105-
} catch (NoSuchFieldException | IllegalAccessException e) {
106-
throw new WebDriverException(e);
100+
protected <B> B getPrivateFieldValue(String fieldName, Class<B> fieldType) {
101+
Class<?> superclass = getClass().getSuperclass();
102+
Throwable recentException = null;
103+
while (superclass != Object.class) {
104+
try {
105+
final Field f = superclass.getDeclaredField(fieldName);
106+
f.setAccessible(true);
107+
return fieldType.cast(f.get(this));
108+
} catch (NoSuchFieldException | IllegalAccessException e) {
109+
recentException = e;
110+
}
111+
superclass = superclass.getSuperclass();
107112
}
113+
throw new WebDriverException(recentException);
108114
}
109115

110-
private void setPrivateFieldValue(String fieldName, Object newValue) {
111-
try {
112-
final Field f = getClass().getSuperclass().getDeclaredField(fieldName);
113-
f.setAccessible(true);
114-
f.set(this, newValue);
115-
} catch (NoSuchFieldException | IllegalAccessException e) {
116-
throw new WebDriverException(e);
116+
protected void setPrivateFieldValue(String fieldName, Object newValue) {
117+
Class<?> superclass = getClass().getSuperclass();
118+
Throwable recentException = null;
119+
while (superclass != Object.class) {
120+
try {
121+
final Field f = superclass.getDeclaredField(fieldName);
122+
f.setAccessible(true);
123+
f.set(this, newValue);
124+
return;
125+
} catch (NoSuchFieldException | IllegalAccessException e) {
126+
recentException = e;
127+
}
128+
superclass = superclass.getSuperclass();
117129
}
130+
throw new WebDriverException(recentException);
118131
}
119132

120-
private Map<String, CommandInfo> getAdditionalCommands() {
133+
protected Map<String, CommandInfo> getAdditionalCommands() {
121134
//noinspection unchecked
122135
return getPrivateFieldValue("additionalCommands", Map.class);
123136
}
124137

125-
private CommandCodec<HttpRequest> getCommandCodec() {
138+
protected CommandCodec<HttpRequest> getCommandCodec() {
126139
//noinspection unchecked
127140
return getPrivateFieldValue("commandCodec", CommandCodec.class);
128141
}
129142

130-
private void setCommandCodec(CommandCodec<HttpRequest> newCodec) {
143+
protected void setCommandCodec(CommandCodec<HttpRequest> newCodec) {
131144
setPrivateFieldValue("commandCodec", newCodec);
132145
}
133146

134-
private void setResponseCodec(ResponseCodec<HttpResponse> codec) {
147+
protected void setResponseCodec(ResponseCodec<HttpResponse> codec) {
135148
setPrivateFieldValue("responseCodec", codec);
136149
}
137150

138-
private HttpClient getClient() {
151+
protected HttpClient getClient() {
139152
//noinspection unchecked
140153
return getPrivateFieldValue("client", HttpClient.class);
141154
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* See the NOTICE file distributed with this work for additional
5+
* information regarding copyright ownership.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package io.appium.java_client.remote;
18+
19+
import static java.util.concurrent.TimeUnit.MILLISECONDS;
20+
21+
import com.google.common.base.Strings;
22+
23+
import okhttp3.ConnectionPool;
24+
import okhttp3.Credentials;
25+
import org.openqa.selenium.remote.http.HttpClient;
26+
import org.openqa.selenium.remote.internal.OkHttpClient;
27+
28+
import java.net.URL;
29+
import java.time.Duration;
30+
import java.util.Objects;
31+
32+
/**
33+
* We must use the customized factory, because the default one
34+
* inside Selenium has retryOnConnectionFailure set to false
35+
* which causes unexpected connection issues, for example:
36+
* https://github.com/appium/java-client/issues/927
37+
*/
38+
public class AppiumHttpClientFactory extends OkHttpClient.Factory {
39+
40+
private final ConnectionPool pool = new ConnectionPool();
41+
private final long connectionTimeout;
42+
private final long readTimeout;
43+
44+
public AppiumHttpClientFactory() {
45+
this(Duration.ofMinutes(2), Duration.ofHours(3));
46+
}
47+
48+
/**
49+
* Creates a factory instance for HttpOK client with customized
50+
* Appium config.
51+
*
52+
* @param connectionTimeout http connection timeout
53+
* @param readTimeout http read timeout
54+
*/
55+
public AppiumHttpClientFactory(Duration connectionTimeout, Duration readTimeout) {
56+
Objects.requireNonNull(connectionTimeout, "Connection timeout cannot be null");
57+
Objects.requireNonNull(readTimeout, "Read timeout cannot be null");
58+
59+
this.connectionTimeout = connectionTimeout.toMillis();
60+
this.readTimeout = readTimeout.toMillis();
61+
}
62+
63+
@Override
64+
public HttpClient createClient(URL url) {
65+
okhttp3.OkHttpClient.Builder client = new okhttp3.OkHttpClient.Builder()
66+
.connectionPool(pool)
67+
.followRedirects(true)
68+
.followSslRedirects(true)
69+
.retryOnConnectionFailure(true)
70+
.readTimeout(readTimeout, MILLISECONDS)
71+
.connectTimeout(connectionTimeout, MILLISECONDS);
72+
73+
String info = url.getUserInfo();
74+
if (!Strings.isNullOrEmpty(info)) {
75+
String[] parts = info.split(":", 2);
76+
String user = parts[0];
77+
String pass = parts.length > 1 ? parts[1] : null;
78+
79+
String credentials = Credentials.basic(user, pass);
80+
81+
client.authenticator((route, response) -> {
82+
if (response.request().header("Authorization") != null) {
83+
return null; // Give up, we've already attempted to authenticate.
84+
}
85+
86+
return response.request().newBuilder()
87+
.header("Authorization", credentials)
88+
.build();
89+
});
90+
}
91+
92+
return new OkHttpClient(client.build(), url);
93+
}
94+
95+
@Override
96+
public void cleanupIdleClients() {
97+
pool.evictAll();
98+
}
99+
}

0 commit comments

Comments
 (0)