NotificationManagerImpl.java
22.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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.granite.security.user.UserManagementService
* com.day.cq.commons.jcr.JcrUtil
* com.day.cq.security.Authorizable
* com.day.cq.wcm.api.PageEvent
* com.day.cq.wcm.api.PageModification
* javax.jcr.Node
* javax.jcr.NodeIterator
* javax.jcr.Property
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.jcr.Workspace
* javax.jcr.query.Query
* javax.jcr.query.QueryManager
* javax.jcr.query.QueryResult
* org.apache.commons.lang.StringUtils
* 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.jackrabbit.api.JackrabbitSession
* org.apache.jackrabbit.api.security.user.Authorizable
* org.apache.jackrabbit.api.security.user.UserManager
* org.apache.sling.api.resource.PersistableValueMap
* org.apache.sling.api.resource.ValueMap
* org.apache.sling.commons.osgi.OsgiUtil
* org.apache.sling.jcr.api.SlingRepository
* org.apache.sling.jcr.resource.JcrModifiablePropertyMap
* org.osgi.service.component.ComponentContext
* org.osgi.service.event.Event
* org.osgi.service.event.EventHandler
* org.slf4j.Logger
*/
package com.day.cq.wcm.notification.impl;
import com.adobe.granite.security.user.UserManagementService;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.cq.wcm.api.PageEvent;
import com.day.cq.wcm.api.PageModification;
import com.day.cq.wcm.notification.Channel;
import com.day.cq.wcm.notification.NotificationContext;
import com.day.cq.wcm.notification.NotificationManager;
import com.day.cq.wcm.notification.NotificationUtil;
import com.day.cq.wcm.notification.Subscription;
import com.day.cq.wcm.notification.impl.ServiceTrackerImpl;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.commons.lang.StringUtils;
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.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.resource.PersistableValueMap;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.resource.JcrModifiablePropertyMap;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
@Component(metatype=1, label="%notificationmanager.name", description="%notificationmanager.description")
@Service(value={EventHandler.class, NotificationManager.class})
@Properties(value={@org.apache.felix.scr.annotations.Property(name="event.topics", value={"com/day/cq/wcm/core/page"}, label="%notificationmanager.topics.name", description="%notificationmanager.topics.description", cardinality=Integer.MAX_VALUE), @org.apache.felix.scr.annotations.Property(name="event.filter", value={"(!(event.application=*))"})})
public class NotificationManagerImpl
extends ServiceTrackerImpl
implements EventHandler,
NotificationManager,
Runnable {
private static final long DEFAULT_WAITING_TIME = 60;
@org.apache.felix.scr.annotations.Property(longValue={60}, label="%waiting.time.name", description="%waiting.time.description")
private static final String PROPERTY_WAITING_TIME = "waiting.time";
public static final String FOLDER_NODETYPE = "sling:Folder";
public static final String PRODUCT_PREFIX = "wcm";
public static final String SUB_PRODUCT_PREFIX = "notification";
private static final String CONFIG_DIR = "config";
private static final String SUBSCRIPTION_NODE = "subscriptions";
private static final String CHANNEL_NODE = "channels";
private static final String NOTIFICATION_SERVICE = "notification-service";
@Reference
protected SlingRepository repository;
@Reference
private UserManagementService userManagementService;
protected final BlockingQueue<Event> queue = new LinkedBlockingQueue<Event>();
protected volatile boolean running = false;
private long waitingTime;
@Override
protected void activate(ComponentContext context) {
super.activate(context);
this.running = true;
this.waitingTime = OsgiUtil.toLong(context.getProperties().get("waiting.time"), (long)60);
Thread t = new Thread(this);
t.start();
}
@Override
protected void deactivate(ComponentContext context) {
this.running = false;
try {
this.queue.put(new Event("something", (Dictionary)null));
}
catch (InterruptedException ignore) {
// empty catch block
}
super.deactivate(context);
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
@Override
public void run() {
while (this.running) {
Event event = null;
try {
event = this.queue.take();
}
catch (InterruptedException e) {
// empty catch block
}
if (event == null || !this.running) continue;
ArrayList<Event> events = new ArrayList<Event>();
this.addEvent(events, event);
try {
Thread.sleep(1000 * this.waitingTime);
}
catch (InterruptedException ignore) {
// empty catch block
}
while (!this.queue.isEmpty()) {
event = this.queue.poll();
this.addEvent(events, event);
}
if (!this.running || this.getSubscriptionNames().size() <= 0) continue;
Session serviceSession = null;
try {
serviceSession = this.repository.loginService("notification-service", null);
this.process(events.toArray((T[])new Event[events.size()]), serviceSession);
continue;
}
catch (Throwable t) {
this.logger.error("Unhandled error during event processing " + t.getMessage(), t);
continue;
}
finally {
if (serviceSession == null) continue;
serviceSession.logout();
serviceSession = null;
continue;
}
}
}
private void addEvent(List<Event> events, Event event) {
if (event.getTopic().equals("com/day/cq/wcm/core/page")) {
Iterator mods = PageEvent.fromEvent((Event)event).getModifications();
while (this.running && mods.hasNext()) {
PageModification m = (PageModification)mods.next();
events.add(m.toEvent());
}
} else {
events.add(event);
}
}
@Override
public boolean subscribe(Authorizable authorizable, Map<String, Object> configuration, Session s) {
if (null == authorizable) {
throw new IllegalArgumentException("authorizable may not be null");
}
if (null == configuration) {
throw new IllegalArgumentException("configuration may not be null");
}
try {
Node notificationNode = NotificationUtil.getNotificationNode(authorizable.getPath(), s);
String relNodePath = "config/subscriptions/" + NotificationUtil.getSubscriptionType(configuration) + '_' + System.currentTimeMillis();
Node subscriptionNode = this.createNodes(notificationNode, relNodePath, "sling:Folder");
for (Map.Entry<String, Object> entry : configuration.entrySet()) {
if (entry.getKey().startsWith("jcr:")) continue;
JcrUtil.setProperty((Node)subscriptionNode, (String)entry.getKey(), (Object)entry.getValue());
}
PersistableValueMap channelConfig = this.getChannelConfiguration(authorizable, configuration, s);
if (channelConfig == null) {
String relChannelNodePath = "config/channels/" + NotificationUtil.getChannelName(configuration);
Node channelsNode = this.createNodes(notificationNode, relChannelNodePath, "sling:Folder");
channelsNode.setProperty("type", NotificationUtil.getChannelName(configuration));
}
s.save();
return true;
}
catch (RepositoryException e) {
this.logger.error("Unable to create new subscription for " + (Object)authorizable, (Throwable)e);
return false;
}
}
@Override
public PersistableValueMap getChannelConfiguration(Authorizable authorizable, Map subscriptionConfig, Session session) {
String channelName = NotificationUtil.getChannelName(subscriptionConfig);
if (channelName != null) {
try {
Node channelsNode = this.getChannelsNode(authorizable, session);
if (channelsNode != null && channelsNode.hasNode(channelName)) {
return new JcrModifiablePropertyMap(channelsNode.getNode(channelName));
}
}
catch (RepositoryException re) {
this.logger.error("Unexpected error during reading of user channel.", (Throwable)re);
}
}
return null;
}
@Override
public Iterator<PersistableValueMap> getChannelConfigurations(Authorizable authorizable, Session session) {
ArrayList<JcrModifiablePropertyMap> configs = new ArrayList<JcrModifiablePropertyMap>();
try {
Node channelsNode = this.getChannelsNode(authorizable, session);
if (channelsNode != null) {
NodeIterator nI = channelsNode.getNodes();
while (nI.hasNext()) {
Node subNode = nI.nextNode();
JcrModifiablePropertyMap properties = new JcrModifiablePropertyMap(subNode);
configs.add(properties);
}
}
}
catch (RepositoryException re) {
this.logger.error("Unexpected error during reading of channel configurations for " + (Object)authorizable, (Throwable)re);
}
return configs.iterator();
}
@Override
public Iterator<PersistableValueMap> getSubscriptionConfigurations(Authorizable authorizable, Session session) {
ArrayList<JcrModifiablePropertyMap> configs = new ArrayList<JcrModifiablePropertyMap>();
try {
Node subscriptionsNode = this.getSubscriptionsNode(authorizable, session);
if (subscriptionsNode != null) {
NodeIterator nI = subscriptionsNode.getNodes();
while (nI.hasNext()) {
Node subNode = nI.nextNode();
JcrModifiablePropertyMap properties = new JcrModifiablePropertyMap(subNode);
configs.add(properties);
}
}
}
catch (RepositoryException re) {
this.logger.error("Unexpected error during reading of subscription configurations for " + (Object)authorizable, (Throwable)re);
}
return configs.iterator();
}
@Override
public boolean unsubscribe(Authorizable authorizable, String path, Session session) {
if (null == authorizable) {
throw new IllegalArgumentException("authorizable may not be null");
}
if (null == path) {
throw new IllegalArgumentException("path may not be null");
}
ArrayList<String> todelete = new ArrayList<String>();
Iterator<PersistableValueMap> configs = this.getSubscriptionConfigurations(authorizable, session);
while (configs.hasNext()) {
PersistableValueMap config = configs.next();
String[] patterns = (String[])config.get("paths", (Object)new String[0]);
if (patterns.length <= 0) continue;
for (String pattern : patterns) {
String subscriptionPath = StringUtils.split((String)pattern, (String)"|")[0];
if (!path.equals(subscriptionPath)) continue;
todelete.add(((JcrModifiablePropertyMap)config).getPath());
}
}
try {
for (String delete : todelete) {
if (!session.itemExists(delete)) continue;
session.removeItem(delete);
}
session.save();
return true;
}
catch (RepositoryException e) {
this.logger.error("failed removing subscription [{}]: {}", (Object)path, (Object)e);
return false;
}
}
public void handleEvent(Event e) {
try {
this.queue.put(e);
}
catch (InterruptedException ignore) {
// empty catch block
}
}
private String buildQueryString() {
StringBuilder builder = new StringBuilder();
builder.append("/jcr:root");
builder.append(this.userManagementService.getAuthorizableRootPath());
builder.append("//");
builder.append("wcm");
builder.append('/');
builder.append("notification");
builder.append('/');
builder.append("config");
builder.append('/');
builder.append("subscriptions");
builder.append("/* [");
boolean first = true;
for (String id : this.getSubscriptionNames()) {
if (!first) {
builder.append(" or ");
}
first = false;
builder.append("@type='");
builder.append(id);
builder.append("'");
}
builder.append("]");
return builder.toString();
}
private NotificationContext createContext(final Session serviceSession, final PersistableValueMap configuration, final Node configurationNode) {
NotificationContext context = new NotificationContext(){
@Override
public Authorizable getAuthorizable() {
try {
String principlePath = NotificationManagerImpl.this.getPrinciplePath(configurationNode);
return ((JackrabbitSession)serviceSession).getUserManager().getAuthorizableByPath(principlePath);
}
catch (RepositoryException e) {
return null;
}
}
@Override
public Session getAdministrativeSession() {
NotificationManagerImpl.this.logger.warn("Deprecated API. Use a service user session instead of a priveleged user session");
return null;
}
@Override
public PersistableValueMap getConfiguration() {
return configuration;
}
@Override
public com.day.cq.security.Authorizable getUser() {
NotificationManagerImpl.this.logger.warn("Deprecated API. Use NotificationContext#getAutharizable() instead");
return null;
}
};
return context;
}
private void process(Event[] events, Session serviceSession) throws RepositoryException {
QueryManager qm = serviceSession.getWorkspace().getQueryManager();
Query q = qm.createQuery(this.buildQueryString(), "xpath");
QueryResult result = q.execute();
NodeIterator ni = result.getNodes();
while (this.running && ni.hasNext()) {
Node subscriptionNode = ni.nextNode();
JcrModifiablePropertyMap properties = new JcrModifiablePropertyMap(subscriptionNode);
String type = NotificationUtil.getSubscriptionType((Map)properties);
Subscription subcription = this.getSubscription(type);
NotificationContext subscriptionContext = this.createContext(serviceSession, (PersistableValueMap)properties, subscriptionNode);
NotificationContext channelContext = null;
Channel channel = null;
boolean hasErrors = false;
for (Event event : events) {
if (hasErrors || !subcription.matches(subscriptionContext, event)) continue;
if (channel == null) {
String channelName = NotificationUtil.getChannelName((Map)properties);
Node channelConfigNode = this.getChannelConfiguration(subscriptionNode, channelName);
JcrModifiablePropertyMap channelConfig = channelConfigNode == null ? null : new JcrModifiablePropertyMap(channelConfigNode);
Channel channel2 = channel = channelConfig == null ? null : this.getChannel(NotificationUtil.getChannelType((Map)channelConfig));
if (channel == null) {
this.logger.error("Subscription {} uses unknown channel {}.", (Object)subscriptionNode.getPath(), (Object)channelName);
hasErrors = true;
} else {
channelContext = this.createContext(serviceSession, (PersistableValueMap)channelConfig, channelConfigNode);
}
}
if (channel == null) continue;
try {
channel.publish(channelContext, event);
continue;
}
catch (Throwable t) {
this.logger.error("Unhandled error during event processing " + t.getMessage(), t);
}
}
}
}
private String getPrinciplePath(Node configNodePath) throws RepositoryException {
Node node = configNodePath;
for (int i = 0; i < 5; ++i) {
node = node.getParent();
}
return node.getPath();
}
private Node getSubscriptionsNode(Authorizable authorizable, Session s) throws RepositoryException {
Node configNode;
Node notificationNode = NotificationUtil.getNotificationNode(authorizable.getPath(), s);
if (notificationNode.hasNode("config") && (configNode = notificationNode.getNode("config")).hasNode("subscriptions")) {
return configNode.getNode("subscriptions");
}
return null;
}
private Node getChannelsNode(Authorizable authorizable, Session s) throws RepositoryException {
Node configNode;
Node notificationNode = NotificationUtil.getNotificationNode(authorizable.getPath(), s);
if (notificationNode.hasNode("config") && (configNode = notificationNode.getNode("config")).hasNode("channels")) {
return configNode.getNode("channels");
}
return null;
}
private Node getChannelConfiguration(Node subscriptionNode, String channelName) throws RepositoryException {
Node channelsNode;
Node configNode = subscriptionNode.getParent().getParent();
if (configNode.hasNode("channels") && (channelsNode = configNode.getNode("channels")).hasNode(channelName)) {
return channelsNode.getNode(channelName);
}
return null;
}
private Node createNodes(Node node, String relNodePath, String nodetype) throws RepositoryException {
String[] pathSplits = relNodePath.split("/");
Node targetNode = node;
for (String name : pathSplits) {
targetNode = targetNode.hasNode(name) ? targetNode.getNode(name) : targetNode.addNode(name, nodetype);
}
return targetNode;
}
@Override
public Iterator<PersistableValueMap> getSubscriptionConfigurations(com.day.cq.security.Authorizable authorizable) {
this.logger.warn("Deprecated API. Use NotificationManager#getSubscriptionConfigurations(org.apache.jackrabbit.api.security.user.Authorizable) instead");
return null;
}
@Override
public Iterator<PersistableValueMap> getChannelConfigurations(com.day.cq.security.Authorizable authorizable) {
this.logger.warn("Deprecated API. Use NotificationManager#getChannelConfiguration(org.apache.jackrabbit.api.security.user.Authorizable) instead");
return null;
}
@Override
public PersistableValueMap getChannelConfiguration(com.day.cq.security.Authorizable authorizable, Map subscriptionConfig) {
this.logger.warn("Deprecated API. Use NotificationManager#getChannelConfiguration(org.apache.jackrabbit.api.security.user.Authorizable, Map) instead");
return null;
}
@Override
public boolean subscribe(com.day.cq.security.Authorizable authorizable, Map<String, Object> configuration) {
this.logger.warn("Deprecated API. Use NotificationManager#subscribe(org.apache.jackrabbit.api.security.user.Authorizable, Map<String, Object>) instead");
return false;
}
@Override
public boolean unsubscribe(com.day.cq.security.Authorizable authorizable, String path) {
this.logger.warn("Deprecated API. Use NotificationManager#unsubscribe(org.apache.jackrabbit.api.security.user.Authorizable, String) instead");
return false;
}
@Override
public Node getNotificationNode(com.day.cq.security.Authorizable authorizable) throws RepositoryException {
this.logger.warn("Deprecated API. Use NotificationManager#getNotificationNode(org.apache.jackrabbit.api.security.user.Authorizable) instead");
return null;
}
@Override
public boolean createSubscription(com.day.cq.security.Authorizable authorizable, ValueMap configuration) {
this.logger.warn("Deprecated API. Use NotificationManager#subscribe(org.apache.jackrabbit.api.security.user.Authorizable, Map<String, Object>) instead");
return false;
}
@Override
public boolean removeSubscription(com.day.cq.security.Authorizable authorizable, PersistableValueMap configuration) {
this.logger.warn("Deprecated API. Use NotificationManager#unsubscribe(org.apache.jackrabbit.api.security.user.Authorizable, String) instead");
return false;
}
protected void bindRepository(SlingRepository slingRepository) {
this.repository = slingRepository;
}
protected void unbindRepository(SlingRepository slingRepository) {
if (this.repository == slingRepository) {
this.repository = null;
}
}
protected void bindUserManagementService(UserManagementService userManagementService) {
this.userManagementService = userManagementService;
}
protected void unbindUserManagementService(UserManagementService userManagementService) {
if (this.userManagementService == userManagementService) {
this.userManagementService = null;
}
}
}