HTTPUtil.java
11.1 KB
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.granite.auth.oauth.AccessTokenProvider
* com.adobe.granite.crypto.CryptoException
* com.adobe.granite.crypto.CryptoSupport
* org.apache.http.NoHttpResponseException
* org.apache.http.auth.AuthScope
* org.apache.http.auth.Credentials
* org.apache.http.auth.UsernamePasswordCredentials
* org.apache.http.client.CredentialsProvider
* org.apache.http.client.HttpClient
* org.apache.http.client.HttpRequestRetryHandler
* org.apache.http.client.config.RequestConfig
* org.apache.http.client.config.RequestConfig$Builder
* org.apache.http.impl.client.BasicCredentialsProvider
* org.apache.http.impl.client.CloseableHttpClient
* org.apache.http.impl.client.HttpClientBuilder
* org.apache.http.message.BasicHeader
* org.apache.http.osgi.services.HttpClientBuilderFactory
* org.apache.http.protocol.HttpContext
* org.apache.sling.api.resource.LoginException
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.api.resource.ResourceResolverFactory
* org.apache.sling.api.resource.ValueMap
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.adobe.cq.dam.mac.sync.helper.impl.http;
import com.adobe.cq.dam.mac.sync.helper.impl.MACTenantConfiguration;
import com.adobe.granite.auth.oauth.AccessTokenProvider;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.apache.http.NoHttpResponseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.osgi.services.HttpClientBuilderFactory;
import org.apache.http.protocol.HttpContext;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HTTPUtil {
public static final int MAX_RETRIES = 1;
public static final int DEFAULT_SO_TIMEOUT = 30000;
private static final String BEARER_AUTHENTICATION_FORMAT = "Bearer %s";
private static final String AUTHORIZATION_HEADER = "Authorization";
private static Logger log = LoggerFactory.getLogger(HTTPUtil.class);
private static final Map<String, Object> REPLICATION_SERVICE_AUTH_INFO = Collections.singletonMap("sling.service.subservice", "dam-replication-helper");
public static HttpClient getClient(int socketTimeout, String tenantURL, HttpClientBuilderFactory httpClientBuilderFactory) {
if (socketTimeout <= 0) {
socketTimeout = 30000;
}
try {
URI uri = new URI(tenantURL);
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(socketTimeout).setSocketTimeout(socketTimeout);
RequestConfig requestConfig = requestConfigBuilder.build();
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler(){
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
boolean sent;
if (executionCount >= 1) {
return false;
}
if (exception instanceof NoHttpResponseException) {
return true;
}
Boolean b = (Boolean)context.getAttribute("http.request_sent");
boolean bl = sent = b != null && b != false;
if (!sent) {
return true;
}
return false;
}
};
CloseableHttpClient client = httpClientBuilderFactory.newBuilder().setDefaultRequestConfig(requestConfig).setRetryHandler(retryHandler).build();
return client;
}
catch (URISyntaxException e) {
log.error("Malformed tenant URL: " + tenantURL, (Throwable)e);
throw new RuntimeException(e);
}
}
public static HttpClient getClient(int socketTimeout, MACTenantConfiguration macConfiguration, ResourceResolverFactory rrf, AccessTokenProvider accessTokenProvider, CryptoSupport crypto, HttpClientBuilderFactory httpClientBuilderFactory) throws LoginException, IOException, URISyntaxException, CryptoException {
if (socketTimeout <= 0) {
socketTimeout = 30000;
}
Object resolver = null;
try {
String password;
UsernamePasswordCredentials defaultCreds = null;
boolean useBasicAuth = (Boolean)macConfiguration.getProperties().get("basicEnabled", (Object)Boolean.FALSE);
if (useBasicAuth) {
password = (String)macConfiguration.getProperties().get("macSyncUserPassword", String.class);
String userName = (String)macConfiguration.getProperties().get("macSyncUser", String.class);
if (password == null || userName == null) {
throw new IllegalArgumentException("username/password not set for basic authentication");
}
if (crypto.isProtected(password)) {
password = crypto.unprotect(password);
}
defaultCreds = new UsernamePasswordCredentials(userName, password);
password = null;
}
password = HTTPUtil.getClient(socketTimeout, macConfiguration.getTenantURL(), macConfiguration.getDAMUser(), useBasicAuth, (Credentials)defaultCreds, rrf, accessTokenProvider, httpClientBuilderFactory);
return password;
}
catch (CryptoException e) {
log.error("Error impersonating the user ", (Throwable)e);
throw e;
}
finally {
if (resolver != null) {
resolver.close();
}
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public static HttpClient getClient(int socketTimeout, String tenantUrl, String damUser, boolean useBasicAuth, Credentials defaultCreds, ResourceResolverFactory rrf, AccessTokenProvider accessTokenProvider, HttpClientBuilderFactory httpClientBuilderFactory) throws CryptoException, IOException, URISyntaxException, LoginException {
if (socketTimeout <= 0) {
socketTimeout = 30000;
}
ResourceResolver resolver = null;
try {
CloseableHttpClient authScope;
CloseableHttpClient client;
URI uri = new URI(tenantUrl);
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(socketTimeout).setSocketTimeout(socketTimeout);
ArrayList<BasicHeader> defaultHeaders = new ArrayList<BasicHeader>();
boolean setCredentials = false;
if ("https".equals(uri.getScheme())) {
if (!useBasicAuth) {
log.debug("* Using OAuth 2.0 Authorization Grants");
if (accessTokenProvider == null) {
log.error("Access token provider is not bind");
throw new IllegalArgumentException("Access token provider is not bind");
}
String keyStoreUser = damUser;
log.debug("* OAuth 2.0 User: {}", (Object)keyStoreUser);
resolver = rrf.getServiceResourceResolver(REPLICATION_SERVICE_AUTH_INFO);
try {
String accessToken = accessTokenProvider.getAccessToken(resolver, keyStoreUser, null);
String authorization = String.format("Bearer %s", accessToken);
BasicHeader header = new BasicHeader("Authorization", authorization);
defaultHeaders.add(header);
}
catch (CryptoException e) {
log.error("Failed to get an access token for user: {} msg: {}", (Object)keyStoreUser, (Object)e.getMessage());
throw e;
}
catch (IOException e) {
log.error("Failed to get an access token for user: {} msg: {}", (Object)keyStoreUser, (Object)e.getMessage());
throw e;
}
} else {
setCredentials = true;
}
} else {
setCredentials = true;
}
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler(){
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
boolean sent;
if (executionCount >= 1) {
return false;
}
if (exception instanceof NoHttpResponseException) {
return true;
}
Boolean b = (Boolean)context.getAttribute("http.request_sent");
boolean bl = sent = b != null && b != false;
if (!sent) {
return true;
}
return false;
}
};
RequestConfig requestConfig = requestConfigBuilder.build();
HttpClientBuilder clientBuilder = httpClientBuilderFactory.newBuilder().setDefaultRequestConfig(requestConfig).setRetryHandler(retryHandler);
if (setCredentials && defaultCreds != null) {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
authScope = new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM);
credentialsProvider.setCredentials((AuthScope)authScope, defaultCreds);
clientBuilder.setDefaultCredentialsProvider((CredentialsProvider)credentialsProvider);
}
if (!defaultHeaders.isEmpty()) {
clientBuilder.setDefaultHeaders(defaultHeaders);
}
authScope = client = clientBuilder.build();
return authScope;
}
catch (URISyntaxException e) {
log.error("Malformed tenant URL: " + tenantUrl, (Throwable)e);
throw e;
}
catch (LoginException e) {
log.error("Error impersonating the user ", (Throwable)e);
throw e;
}
finally {
if (resolver != null) {
resolver.close();
}
}
}
}