5
5
import com .github .benmanes .caffeine .cache .Caffeine ;
6
6
import edu .umd .cs .findbugs .annotations .NonNull ;
7
7
import hudson .Extension ;
8
+ import hudson .ProxyConfiguration ;
8
9
import hudson .model .AbstractItem ;
9
10
import hudson .model .Action ;
10
11
import hudson .model .Computer ;
35
36
import java .util .concurrent .TimeUnit ;
36
37
import java .util .stream .Collectors ;
37
38
39
+ import static com .microsoft .jenkins .azuread .AzureSecurityRealm .addProxyToHttpClientIfRequired ;
40
+
38
41
/**
39
42
* Proxies calls to the Microsoft Graph API.
40
43
*/
41
44
@ Extension
42
45
@ Restricted (NoExternalUse .class )
43
46
public class GraphProxy implements RootAction , StaplerProxy {
44
-
45
- private static final OkHttpClient CLIENT = new OkHttpClient ();
46
47
private static final int TEN = 10 ;
47
48
private final Cache <String , AccessToken > tokenCache = Caffeine .newBuilder ()
48
49
.expireAfterWrite (TEN , TimeUnit .MINUTES )
49
50
.build ();
50
51
51
52
private AccessControlled accessControlled ;
53
+ private static final OkHttpClient DEFAULT_CLIENT = new OkHttpClient ();
52
54
53
55
@ Override
54
56
public String getIconFileName () {
@@ -122,19 +124,19 @@ public Collection<? extends Action> createFor(@NonNull Computer target) {
122
124
return Collections .singletonList (new GraphProxy (target ));
123
125
}
124
126
}
125
-
126
127
public void doDynamic (StaplerRequest request , StaplerResponse response ) throws IOException {
127
128
proxy (request , response );
128
129
}
129
130
130
131
private void proxy (StaplerRequest request , StaplerResponse response ) throws IOException {
132
+ OkHttpClient client = getClient ();
131
133
String baseUrl = getBaseUrl ();
132
134
String token = getToken ();
133
135
134
136
String url = buildUrl (request , baseUrl );
135
137
Request okRequest = buildRequest (request , token , url );
136
138
137
- try (Response okResp = CLIENT .newCall (okRequest ).execute ()) {
139
+ try (Response okResp = client .newCall (okRequest ).execute ()) {
138
140
String contentType = okResp .header ("Content-Type" , "application/json" );
139
141
140
142
response .setContentType (contentType );
@@ -157,6 +159,17 @@ private void proxy(StaplerRequest request, StaplerResponse response) throws IOEx
157
159
}
158
160
}
159
161
162
+ /**
163
+ * Prefers the default client for performance, proxy users will get a new instance each time.
164
+ */
165
+ private OkHttpClient getClient () {
166
+ ProxyConfiguration proxyConfiguration = Jenkins .get ().getProxy ();
167
+ if (proxyConfiguration != null && StringUtils .isNotBlank (proxyConfiguration .getName ())) {
168
+ return addProxyToHttpClientIfRequired (new OkHttpClient ().newBuilder ()).build ();
169
+ }
170
+ return DEFAULT_CLIENT ;
171
+ }
172
+
160
173
private String getToken () {
161
174
SecurityRealm securityRealm = Jenkins .get ().getSecurityRealm ();
162
175
if (securityRealm instanceof AzureSecurityRealm ) {
0 commit comments