ImpressionsImporter.java
15.8 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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.day.cq.commons.inherit.HierarchyNodeInheritanceValueMap
* com.day.cq.polling.importer.ImportException
* com.day.cq.polling.importer.Importer
* com.day.cq.statistics.StatisticsService
* com.day.cq.wcm.webservicesupport.Configuration
* com.day.cq.wcm.webservicesupport.ConfigurationManager
* com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory
* com.day.crx.statistics.Entry
* javax.jcr.Node
* javax.jcr.PathNotFoundException
* javax.jcr.Property
* javax.jcr.RepositoryException
* javax.jcr.Session
* org.apache.felix.scr.annotations.Component
* 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.api.resource.Resource
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.api.resource.ValueMap
* org.apache.sling.commons.json.JSONArray
* org.apache.sling.commons.json.JSONException
* org.apache.sling.commons.json.JSONObject
* org.apache.sling.commons.osgi.OsgiUtil
* org.apache.sling.discovery.InstanceDescription
* org.apache.sling.discovery.TopologyEvent
* org.apache.sling.discovery.TopologyEvent$Type
* org.apache.sling.discovery.TopologyEventListener
* org.apache.sling.discovery.TopologyView
* org.apache.sling.settings.SlingSettingsService
* org.osgi.service.component.ComponentContext
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.day.cq.analytics.sitecatalyst;
import com.day.cq.analytics.sitecatalyst.ImpressionsEntry;
import com.day.cq.analytics.sitecatalyst.SitecatalystException;
import com.day.cq.analytics.sitecatalyst.SitecatalystUtil;
import com.day.cq.analytics.sitecatalyst.SitecatalystWebservice;
import com.day.cq.commons.inherit.HierarchyNodeInheritanceValueMap;
import com.day.cq.polling.importer.ImportException;
import com.day.cq.polling.importer.Importer;
import com.day.cq.statistics.StatisticsService;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory;
import com.day.crx.statistics.Entry;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Dictionary;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.discovery.InstanceDescription;
import org.apache.sling.discovery.TopologyEvent;
import org.apache.sling.discovery.TopologyEventListener;
import org.apache.sling.discovery.TopologyView;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Deprecated
@Component(metatype=1, label="Day CQ Analytics SiteCatalyst Impressions Importer", description="Imports SiteCatalyst Page Impressions periodically into CQ")
@Service
@Properties(value={@org.apache.felix.scr.annotations.Property(name="importer.scheme", value={"sitecatalyst"}, propertyPrivate=1)})
public class ImpressionsImporter
implements Importer,
TopologyEventListener {
private final Logger log;
@org.apache.felix.scr.annotations.Property(label="Import interval", description="Import interval in milliseconds. Default is set to 43200000 (12h).", longValue={43200000})
protected static final String REPORT_INTERVAL = "cq.analytics.sitecatalyst.importer.inverval";
private static final long DEFAULT_INTERVAL = 43200000;
private long reportInterval;
@org.apache.felix.scr.annotations.Property(label="Enabled", description="Indicator if importer is enabled or disabled.", boolValue={1})
private static final String ENABLED = "cq.analytics.sitecatalyst.importer.enabled";
private static final boolean DEFAULT_ENABLED = false;
private boolean enabled;
@Reference
private SlingSettingsService settingsService;
@Reference
private SitecatalystWebservice webservice;
@Reference
private StatisticsService statService;
@Reference
private ConfigurationManagerFactory cfgManagerFactory;
private boolean isLeader;
public ImpressionsImporter() {
this.log = LoggerFactory.getLogger(this.getClass());
this.isLeader = false;
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
public void importData(String scheme, String dataSource, Resource target) throws ImportException {
block30 : {
if (this.enabled) {
if (!this.isLeader) {
this.log.info("Import skipped on slave instance");
return;
}
try {
Resource pageResource = target.getParent().getParent();
HierarchyNodeInheritanceValueMap pageProperties = new HierarchyNodeInheritanceValueMap(pageResource);
Node analytics = (Node)target.getParent().adaptTo(Node.class);
String lastAttempt = "0";
if (analytics.hasProperty("cq:lastAttempt")) {
lastAttempt = analytics.getProperty("cq:lastAttempt").getString();
}
Configuration configuration = null;
String[] services = (String[])pageProperties.getInherited("cq:cloudserviceconfigs", (Object)new String[0]);
ConfigurationManager cfgManager = this.cfgManagerFactory.getConfigurationManager(target.getResourceResolver());
if (services.length > 0) {
configuration = cfgManager.getConfiguration("sitecatalyst", services);
}
if (configuration == null) {
this.log.error("SiteCatalyst configuration not found");
return;
}
if (this.isImporterDisabledFromConfig(configuration)) {
return;
}
String reportSuiteID = SitecatalystUtil.getReportSuites(this.settingsService, configuration);
if (lastAttempt.startsWith("waiting")) {
String reportID = lastAttempt.replace("waiting-", "");
try {
String response = this.webservice.getReport(configuration, reportID);
JSONObject jsonObj = new JSONObject(response);
JSONObject report = jsonObj.optJSONObject("report");
if (report != null) {
JSONArray data = report.getJSONArray("data");
String lastAttemptDate = analytics.getProperty("cq:lastAttemptDate").getString();
String statsBasePath = "/var/statistics/pages" + analytics.getPath().replace("/jcr:content/analytics", "");
this.log.info("Report contains data items: " + data.length());
for (int i = 0; i < data.length(); ++i) {
JSONObject pageData = data.getJSONObject(i);
this.setStatsData(statsBasePath, lastAttemptDate, pageData.getString("name"), pageData.getJSONArray("counts").getString(0), target.getResourceResolver(), this.statService);
}
this.log.info("Report " + reportID + " imported");
break block30;
}
Long errorId = jsonObj.optLong("error");
String errorMsg = jsonObj.optString("error_description");
this.log.warn("Report " + reportID + " failed due to (error:" + errorId + "): " + errorMsg);
}
catch (SitecatalystException e) {
this.log.error("Call to Sitecatalyst failed", (Throwable)e);
}
catch (JSONException e) {
this.log.error("Parsing JSON response failed", (Throwable)e);
}
finally {
if (analytics.getSession().hasPendingChanges()) {
analytics.setProperty("cq:lastAttempt", Long.toString(System.currentTimeMillis()));
analytics.getSession().save();
}
}
}
long last = Long.parseLong(lastAttempt);
if (last + this.reportInterval >= System.currentTimeMillis()) break block30;
if (reportSuiteID == null) {
this.log.warn("cannot import data since no valid report suite ID was found");
return;
}
try {
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
cal.add(5, -1);
String date = dateFormat.format(cal.getTime());
String response = this.webservice.queuePageViewReport(configuration, reportSuiteID, date);
JSONObject jsonObj = new JSONObject(response);
Long reportID = jsonObj.optLong("reportID");
if (reportID != 0) {
analytics.setProperty("cq:lastAttempt", "waiting-" + reportID);
analytics.setProperty("cq:lastAttemptDate", date);
this.log.info("Report queued: " + reportID + " for " + reportSuiteID + " and " + date);
break block30;
}
Long errorId = jsonObj.optLong("error");
String errorMsg = jsonObj.optString("error_description");
this.log.warn(jsonObj.toString());
this.log.warn("queueing report failed due to (error:" + errorId + "): " + errorMsg);
analytics.setProperty("cq:lastAttempt", Long.toString(System.currentTimeMillis()));
}
catch (SitecatalystException e) {
this.log.error("Call to SiteCatalyst failed", (Throwable)e);
analytics.setProperty("cq:lastAttempt", Long.toString(System.currentTimeMillis()));
}
catch (JSONException e) {
this.log.error("Parsing JSON response failed", (Throwable)e);
analytics.setProperty("cq:lastAttempt", Long.toString(System.currentTimeMillis()));
}
finally {
if (analytics.getSession().hasPendingChanges()) {
analytics.getSession().save();
}
}
}
catch (PathNotFoundException e) {
this.log.error("Reading analytics data failed for " + target.getPath(), (Throwable)e);
}
catch (RepositoryException e) {
this.log.error("Reading analytics data failed", (Throwable)e);
}
}
}
}
private void setStatsData(String basePath, String date, String name, String count, ResourceResolver resolver, StatisticsService statService) {
long views;
ValueMap statsConfig;
String statsPath = basePath;
name = !name.equals("home") ? "/" + name.replace(":", "/") : "";
statsPath = statsPath + name + "/.stats/";
Resource dayStats = resolver.getResource(statsPath = statsPath + date.replace("-", "/"));
if (dayStats != null && (views = ((Long)(statsConfig = (ValueMap)dayStats.adaptTo(ValueMap.class)).get("views", Long.class)).longValue()) == Long.parseLong(count)) {
return;
}
ImpressionsEntry view = new ImpressionsEntry(basePath, name, date, Long.parseLong(count));
try {
statService.addEntry((Entry)view);
}
catch (RepositoryException e) {
this.log.error("adding stats entry failed", (Throwable)e);
}
}
private boolean isImporterDisabledFromConfig(Configuration config) {
boolean disableAuthor = (Boolean)config.getInherited("disableImportPageImpressionsAuthor", (Object)false);
boolean disablePublish = (Boolean)config.getInherited("disableImportPageImpressionsPublish", (Object)false);
Set runmodes = this.settingsService.getRunModes();
if (disableAuthor && runmodes.contains("author")) {
return true;
}
if (disablePublish && runmodes.contains("publish")) {
return true;
}
return false;
}
protected void activate(ComponentContext componentContext) {
Dictionary config = componentContext.getProperties();
this.reportInterval = OsgiUtil.toLong(config.get("cq.analytics.sitecatalyst.importer.inverval"), (long)43200000);
this.enabled = OsgiUtil.toBoolean(config.get("cq.analytics.sitecatalyst.importer.enabled"), (boolean)false);
}
public void handleTopologyEvent(TopologyEvent event) {
if (event.getType() == TopologyEvent.Type.TOPOLOGY_CHANGED || event.getType() == TopologyEvent.Type.PROPERTIES_CHANGED || event.getType() == TopologyEvent.Type.TOPOLOGY_INIT) {
this.isLeader = event.getNewView().getLocalInstance().isLeader();
} else if (event.getType() == TopologyEvent.Type.TOPOLOGY_CHANGING) {
this.isLeader = false;
}
}
protected void bindCfgManager(ConfigurationManager cfg) {
throw new UnsupportedOperationException();
}
protected void unbindCfgManager(ConfigurationManager cfg) {
throw new UnsupportedOperationException();
}
protected void bindSettingsService(SlingSettingsService slingSettingsService) {
this.settingsService = slingSettingsService;
}
protected void unbindSettingsService(SlingSettingsService slingSettingsService) {
if (this.settingsService == slingSettingsService) {
this.settingsService = null;
}
}
protected void bindWebservice(SitecatalystWebservice sitecatalystWebservice) {
this.webservice = sitecatalystWebservice;
}
protected void unbindWebservice(SitecatalystWebservice sitecatalystWebservice) {
if (this.webservice == sitecatalystWebservice) {
this.webservice = null;
}
}
protected void bindStatService(StatisticsService statisticsService) {
this.statService = statisticsService;
}
protected void unbindStatService(StatisticsService statisticsService) {
if (this.statService == statisticsService) {
this.statService = null;
}
}
protected void bindCfgManagerFactory(ConfigurationManagerFactory configurationManagerFactory) {
this.cfgManagerFactory = configurationManagerFactory;
}
protected void unbindCfgManagerFactory(ConfigurationManagerFactory configurationManagerFactory) {
if (this.cfgManagerFactory == configurationManagerFactory) {
this.cfgManagerFactory = null;
}
}
}