SitecatalystHttpClientImpl.java
17.4 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.granite.crypto.CryptoException
* com.adobe.granite.crypto.CryptoSupport
* com.day.cq.wcm.webservicesupport.Configuration
* javax.jcr.RepositoryException
* org.apache.commons.httpclient.Header
* org.apache.commons.httpclient.HttpClient
* org.apache.commons.httpclient.HttpException
* org.apache.commons.httpclient.HttpMethod
* org.apache.commons.httpclient.URI
* org.apache.commons.httpclient.methods.PostMethod
* org.apache.commons.httpclient.methods.RequestEntity
* org.apache.commons.httpclient.methods.StringRequestEntity
* org.apache.felix.scr.annotations.Activate
* org.apache.felix.scr.annotations.Component
* org.apache.felix.scr.annotations.Deactivate
* org.apache.felix.scr.annotations.Properties
* org.apache.felix.scr.annotations.Property
* org.apache.felix.scr.annotations.Reference
* org.apache.felix.scr.annotations.Service
* org.apache.sling.commons.osgi.PropertiesUtil
* org.osgi.service.component.ComponentContext
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.day.cq.analytics.sitecatalyst.impl;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;
import com.day.cq.analytics.sitecatalyst.SitecatalystException;
import com.day.cq.analytics.sitecatalyst.SitecatalystHttpClient;
import com.day.cq.analytics.sitecatalyst.util.AuthenticationHelper;
import com.day.cq.analytics.sitecatalyst.util.HttpClientUtils;
import com.day.cq.wcm.webservicesupport.Configuration;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Dictionary;
import java.util.List;
import java.util.TimeZone;
import javax.jcr.RepositoryException;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(metatype=1, label="Adobe AEM Analytics HTTP Client", description="HTTP Client for Analytics API")
@Service
@Properties(value={@Property(name="service.description", value={"SiteCatalyst HTTP Client"})})
public class SitecatalystHttpClientImpl
implements SitecatalystHttpClient {
private final Logger log;
private static final String CFG_DATACENTER_URLS = "cq.analytics.sitecatalyst.service.datacenter.url";
private static final String CFG_DEV_HOSTNAME_PATTERNS = "devhostnamepatterns";
private static final String CFG_APPKEY = "applicationkey";
private static final String CFG_TOKENBYPASSSECRET = "tokenbypasssecret";
private static final String CFG_PROXYUSER = "proxyuser";
private static final String CFG_PROXYUSERSECRET = "proxyusersecret";
private static final Integer PRIME = 78593;
@Reference
private CryptoSupport cryptoSupport;
@Property(name="cq.analytics.sitecatalyst.service.datacenter.url", label="Data center URL", description="Default data center URL", value={"https://api.omniture.com/admin/1.4/rest/"})
private List<String> dataCenterURLs;
@Property(name="devhostnamepatterns", label="Hostname patterns", description="Development machines hostname regular expression patterns", value={".*(\\.dev|\\.ut1)+\\.omniture\\.com$"}, cardinality=1024)
private List<String> devHostnames;
@Property(name="applicationkey", label="Application key", description="SiteCatalyst application key", value={"a1729166-7b52-2914-f15b-3834a2e118aa"}, propertyPrivate=1)
private String appKey;
@Property(name="tokenbypasssecret", label="Token bypass secret", description="SiteCatalyst secret to bypass token count", value={"MmD2*Oafei"}, propertyPrivate=1)
private String tokenBypassSecret;
@Property(name="proxyuser", label="Proxy user", description="SiteCatalyst proxy user (i.e. Company:Username)", propertyPrivate=1)
private String proxyUser;
@Property(name="proxyusersecret", label="Proxy user secret", description="SiteCatalyst secret for proxy user", value={"MmD2*Oafei"}, propertyPrivate=1)
private String proxyUserSecret;
private HttpClient httpClient;
public SitecatalystHttpClientImpl() {
this.log = LoggerFactory.getLogger(this.getClass());
this.dataCenterURLs = new ArrayList<String>();
this.devHostnames = new ArrayList<String>();
}
@Override
public String executeProxyUser(String method, String data) throws SitecatalystException {
return this.execute(null, method, data, true, null, null, null);
}
@Override
public String execute(String method, String data, String company, String username, String secret) throws SitecatalystException {
return this.execute(null, method, data, false, company, username, secret);
}
@Override
public String execute(String datacenter, String method, String data, String company, String username, String secret) throws SitecatalystException {
return this.execute(datacenter, method, data, false, company, username, secret);
}
@Override
public String execute(String method, String data, Configuration configuration) throws SitecatalystException {
HttpMethod httpMethod = null;
try {
String company = (String)configuration.getInherited("company", (Object)null);
String username = (String)configuration.getInherited("username", (Object)null);
String secret = (String)configuration.getInherited("secret", (Object)null);
String server = (String)configuration.getInherited("server", (Object)null);
if (server == null) {
this.log.warn("Server property is missing in configuration {}", (Object)configuration.getPath());
if (!this.dataCenterURLs.isEmpty()) {
server = this.dataCenterURLs.get(0);
this.log.debug("Using default datacenter URL {}", (Object)server);
}
}
server = this.upgradeServerToAPI14(server);
PostMethod request = new PostMethod(server + "?method=" + method);
request.setRequestEntity((RequestEntity)new StringRequestEntity(data, "application/json", "UTF-8"));
httpMethod = this.execute((HttpMethod)request, false, company, username, secret);
String string = this.consumeResponse(httpMethod);
return string;
}
catch (IOException e) {
this.log.warn("I/O Error while connecting: {}", (Object)e.getMessage());
throw new SitecatalystException("not online", e);
}
catch (CryptoException e) {
this.log.warn("Internal error while connecting: {}", (Object)e.getMessage());
throw new SitecatalystException("Internal Error", (Throwable)e);
}
finally {
if (httpMethod != null) {
httpMethod.releaseConnection();
}
}
}
private String upgradeServerToAPI14(String oldServer) {
if (oldServer != null) {
String upgradedServer = oldServer.replaceAll("1\\.[0-3]", "1.4");
if (!upgradedServer.equals(oldServer)) {
this.log.info("Analytics servers using pre-1.4 API version are not supported anymore. Converted server URL to use 1.4 API Version: " + oldServer + " -> " + upgradedServer);
}
return upgradedServer;
}
return null;
}
@Override
public String execute(java.net.URI uri, String data, Configuration configuration) throws SitecatalystException {
HttpMethod httpMethod = null;
try {
String uriS = this.upgradeServerToAPI14(uri.toString());
PostMethod request = new PostMethod(uriS);
request.setRequestEntity((RequestEntity)new StringRequestEntity(data, "application/xml", "UTF-8"));
httpMethod = this.execute((HttpMethod)request, false, (String)configuration.getInherited("company", (Object)""), (String)configuration.getInherited("username", (Object)""), (String)configuration.getInherited("secret", (Object)""));
String string = this.consumeResponse(httpMethod);
return string;
}
catch (Exception e) {
throw new SitecatalystException(e.getMessage(), e);
}
finally {
if (httpMethod != null) {
httpMethod.releaseConnection();
}
}
}
private String execute(String datacenter, String method, String data, boolean isProxyUser, String company, String username, String secret) throws SitecatalystException {
HttpMethod httpMethod = null;
try {
if (datacenter == null && this.dataCenterURLs.size() > 0) {
this.log.debug("No data center URL provided, using service default.");
datacenter = this.dataCenterURLs.get(0);
}
if (datacenter == null) {
throw new SitecatalystException("No valid end point given");
}
datacenter = this.upgradeServerToAPI14(datacenter);
PostMethod request = new PostMethod(datacenter + "?method=" + method);
request.setRequestEntity((RequestEntity)new StringRequestEntity(data, "application/json", "UTF-8"));
httpMethod = this.execute((HttpMethod)request, isProxyUser, company, username, secret);
Header contentType = httpMethod.getResponseHeader("Content-Type");
if (contentType != null && !contentType.getValue().contains("application/json")) {
throw new SitecatalystException("Response is of unsupported content-type, please check end point.");
}
String string = this.consumeResponse(httpMethod);
return string;
}
catch (IOException e) {
this.log.error("I/O Error while connecting: {}", (Object)e.getMessage());
throw new SitecatalystException("not online", e);
}
catch (Exception e) {
this.log.error("Internal error while connecting: {}", (Object)e.getMessage());
throw new SitecatalystException(e.getMessage(), e);
}
finally {
if (httpMethod != null) {
httpMethod.releaseConnection();
}
}
}
private HttpMethod execute(HttpMethod method, boolean isProxyUser, String companyname, String username, String secret) throws HttpException, IOException, CryptoException {
URI uri = method.getURI();
String hostName = uri.getHost();
if (uri.getScheme() != null && uri.getScheme().equals("https") && this.isDev(hostName)) {
HttpClientUtils.allowSelfSigned(this.httpClient, hostName, uri.getPort());
URI relUri = new URI(null, null, uri.getPath(), uri.getQuery(), uri.getFragment());
method.setURI(relUri);
} else {
method.setURI(uri);
}
Date now = new Date();
byte[] nonce = this.generateNonce();
String created = this.generateTimestamp(now);
String securityHeader = null;
if (isProxyUser) {
if (companyname == null || username == null) {
String[] serviceUser = this.proxyUser.split("/");
if (serviceUser != null && serviceUser.length == 2) {
companyname = serviceUser[0];
username = serviceUser[1];
} else {
this.log.warn("Method call with isProxyUser=true and no proxy user configured.");
}
}
securityHeader = this.getAppKeySecurityHeader(nonce, username, companyname, created);
} else if (companyname != null && username != null && secret != null) {
String wsUsername = username + ":" + companyname;
if (this.cryptoSupport.isProtected(secret)) {
secret = this.cryptoSupport.unprotect(secret);
}
securityHeader = this.getSecurityHeader(nonce, wsUsername, secret, created);
}
if (securityHeader != null) {
method.addRequestHeader("X-WSSE", securityHeader);
}
this.httpClient.executeMethod(method);
return method;
}
private String consumeResponse(HttpMethod method) throws IOException {
String line;
StringBuffer sb = new StringBuffer();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
while ((line = responseReader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
private String getSecurityHeader(byte[] nonce, String username, String secret, String created) throws UnsupportedEncodingException {
String password64 = AuthenticationHelper.getBase64Digest(nonce, created.getBytes(), secret.getBytes());
StringBuffer header = new StringBuffer();
header.append("UsernameToken Username=\"");
header.append(username);
header.append("\", ");
header.append("PasswordDigest=\"");
header.append(password64.trim());
header.append("\", ");
header.append("Nonce=\"");
header.append(AuthenticationHelper.base64Encode(nonce).trim());
header.append("\", ");
header.append("Created=\"");
header.append(created);
header.append("\", ");
header.append("appkey=\"");
header.append(this.appKey);
header.append("\", ");
header.append("appdigest=\"");
header.append(AuthenticationHelper.getBase64DigestKey(nonce, this.tokenBypassSecret.getBytes()));
header.append("\", ");
header.append("appnonce=\"");
header.append(AuthenticationHelper.base64Encode(nonce).trim());
header.append("\"");
return header.toString();
}
private String getAppKeySecurityHeader(byte[] nonce, String username, String companyname, String created) throws UnsupportedEncodingException {
StringBuffer header = new StringBuffer();
header.append("UsernameToken ");
header.append("Created=\"");
header.append(created);
header.append("\", ");
header.append("appkey=\"");
header.append(this.appKey);
header.append("\", ");
header.append("appdigest=\"");
header.append(AuthenticationHelper.getBase64DigestKey(nonce, this.proxyUserSecret.getBytes()));
header.append("\", ");
header.append("appnonce=\"");
header.append(AuthenticationHelper.base64Encode(nonce).trim());
header.append("\", ");
header.append("proxyuser=\"");
header.append(username);
header.append("\", ");
header.append("proxycompany=\"");
header.append(companyname);
header.append("\"");
return header.toString();
}
private boolean isDev(String hostName) {
for (String pattern : this.devHostnames) {
if (!hostName.matches(pattern)) continue;
return true;
}
return false;
}
private byte[] generateNonce() {
String nonce = String.valueOf(Math.random() * (double)PRIME.intValue());
return nonce.getBytes();
}
private String generateTimestamp(Date date) {
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormatter.format(date);
}
@Activate
protected void activate(ComponentContext ctx) throws RepositoryException {
Dictionary props = ctx.getProperties();
String[] dc = PropertiesUtil.toStringArray(props.get("cq.analytics.sitecatalyst.service.datacenter.url"));
this.dataCenterURLs.addAll(Arrays.asList(dc));
String[] hostnames = PropertiesUtil.toStringArray(props.get("devhostnamepatterns"));
this.devHostnames.addAll(Arrays.asList(hostnames));
this.appKey = PropertiesUtil.toString(props.get("applicationkey"), (String)"");
this.tokenBypassSecret = PropertiesUtil.toString(props.get("tokenbypasssecret"), (String)"");
this.proxyUser = PropertiesUtil.toString(props.get("proxyuser"), (String)"");
this.proxyUserSecret = PropertiesUtil.toString(props.get("proxyusersecret"), (String)"");
this.httpClient = HttpClientUtils.newMultiThreaded();
}
@Deactivate
protected void deactivate(ComponentContext ctx) {
HttpClientUtils.shutdown(this.httpClient);
}
protected void bindCryptoSupport(CryptoSupport cryptoSupport) {
this.cryptoSupport = cryptoSupport;
}
protected void unbindCryptoSupport(CryptoSupport cryptoSupport) {
if (this.cryptoSupport == cryptoSupport) {
this.cryptoSupport = null;
}
}
}